- A Brief Intro To C++ & Its History
- The Detailed History & Timeline Of C++ (With Infographic)
- Importance Of C++
- Versions Of C++ Language
- Structure Of A C++ Program
- Comparison With Other Popular Programming Languages
- Conclusion
- Frequently Asked Questions
- Test Your Skills: Quiz Time
- What Are Variables In C++?
- Declaration & Definition Of Variables In C++
- Variable Initialization In C++
- Rules & Regulations For Naming Variables In C++ Language
- Different Types Of Variables In C++
- Different Types of Variable Initialization In C++
- Conclusion
- Frequently Asked Questions
- Test Your Skills: Quiz Time
- What Are Primitive Data Types In C++?
- Derived Data Types In C++
- User-Defined Data Types In C++
- Abstract Data Types In C++
- Data Type Modifiers In C++
- Declaring Variables With Auto Keyword
- Conclusion
- Frequently Asked Questions
- Test Your Skills: Quiz Time
- Structure Of C++ Program: Components
- Segment 1: Documentation Section Of Structure Of C++ Program (With Example)
- Segment 2: Preprocessing & Namespace (Linking) Section Of CPP Program
- Segment 3: Definition Section In Structure of a C++ Program (With Examples)
- Segment 4: Main Function In Structure Of A C++ Program (With Example)
- Compilation & Execution Of C++ Programs | Step-by-Step Explanation
- Explaining Structure Of C++ Program With Suitable Example
- Conclusion
- Frequently Asked Questions
- Test Your Skills: Quiz Time
- What is Typedef in C++?
- The Role & Applications of Typedef in C++
- Basic Syntax for typedef in C++
- How Does typedef Work in C++?
- How to Use Typedef in C++ With Examples? (Multiple Data Types)
- The Difference Between #define & Typedef in C++
- Conclusion
- Frequently Asked Questions
- Test Your Skills: Quiz Time
- What Are Strings In C++?
- Types Of Strings In C++
- How To Declare & Initialize C-Style Strings In C++ Programs?
- How To Declare & Initialize Strings In C++ Using String Keyword?
- List Of String Functions In C++
- Operations On Strings Using String Functions In C++
- Concatenation Of Strings In C++
- How To Convert Int To Strings In C++
- Conclusion
- Frequently Asked Questions
- Test Your Skills: Quiz Time
- What Is String Concatenation In C++?
- How To Concatenate Two Strings In C++ Using The ‘+' Operator?
- String Concatenation Using The strcat( ) Function
- Concatenation Of Two Strings In C++ Using Loops
- String Concatenation Using The append() Function
- C++ String Concatenation Using The Inheritance Of Class
- Concatenate Two Strings In C++ With The Friend and strcat() Functions
- Why Do We Need To Concatenate Two Strings?
- How To Reverse Concatenation Of Strings In C++?
- Conclusion
- Frequently Asked Questions
- Test Your Skills: Quiz Time
- What Is Find In String C++?
- What Is A Substring?
- How To Find A Substring In A String In C++?
- How To Find A Character In String C++?
- Find All Substrings From A Given String In C++
- Index Substring In String In C++ From A Specific Start To A Specific Length
- Conclusion
- Frequently Asked Questions
- Test Your Skills: Quiz Time
- What Are Pointers In C++?
- Pointer Declaration In C++
- How To Initialize And Use Pointers In C++?
- Different Types Of Pointers In C++
- References & Pointers In C++
- Arrays And Pointers In C++
- String Literals & Pointers In C++
- Pointers To Pointers In C++ (Double Pointers)
- Arithmetic Operation On Pointers In C++
- Advantages Of Pointers In C++
- Some Common Mistakes To Avoid With Pointers In Cpp
- Conclusion
- Frequently Asked Questions
- Test Your Skills: Quiz Time
- Understanding Pointers In C++
- What Is Pointer To Object In C++?
- Declaration And Use Of Object Pointers In C++
- Advantages Of Pointer To Object In C++
- Pointer To Objects In C++ With Arrow Operator
- An Array Of Objects Using Pointers In C++
- Base Class Pointer For Derived Class Object In C++
- Conclusion
- Frequently Asked Questions
- Test Your Skills: Quiz Time
- What Is 'This' Pointer In C++?
- Defining ‘this’ Pointer In C++
- Example Of 'this' Pointer In C++
- Describing The Constness Of 'this' Pointer In C++
- Important Uses Of 'this' Pointer In C++
- Method Chaining Using 'this' Pointer In C++
- C++ Programs To Show Application Of 'This' Pointer
- How To Delete The ‘this’ Pointer In C++?
- Conclusion
- Frequently Asked Questions
- Test Your Skills: Quiz Time
- What is Reference?
- What is Pointer?
- Comparison Table Of C++ Pointer Vs. Reference
- Differences Between Reference And Pointer: A Detailed Explanation
- Why Are References Less Powerful Than Pointers?
- Conclusion
- Frequently Asked Questions
- Test Your Skills: Quiz Time
- How To Declare A 2D Array In C++?
- C++ Multi-Dimensional Arrays
- Ways To Initialize A 2D Array In C++
- Methods To Dynamically Allocate A 2D Array In C++
- Accessing/ Referencing Two-Dimensional Array Elements
- How To Initialize A Two-Dimensional Integer Array In C++?
- How To Initialize A Two-Dimensional Character Array?
- How To Enter Data In Two-Dimensional Array In C++?
- Conclusion
- Frequently Asked Questions
- What Are Arrays Of Strings In C++?
- Different Ways To Create String Arrays In C++
- How To Access The Elements Of A String Array In C++?
- How To Convert Char Array To String?
- Conclusion
- Frequently Asked Questions
- What is Memory Allocation in C++ & Why Do We Need It?
- How Does Dynamic Memory Allocation Work?
- The new Operator in C++
- The delete Operator in C++
- Dynamic Memory Allocation in C++ | Arrays
- Did You Know: Companies That Ask About Dynamic Memory Allocation
- Dynamic Memory Allocation in C++ | Objects
- Deallocation of Dynamic Memory in C++
- malloc(), calloc(), and free() Functions in C/C++
- Applications of Dynamic Memory Allocation in C++
- Conclusion
- Frequently Asked Questions
- Test Your Skills: Quiz Time
- What Is A Substring In C++ (Substr C++)?
- Example for substr() in C++ | Finding Substring Using Positive and Negative Indices
- Understanding substr() Basics with Examples
- Use Cases/ Examples of substr() in C++
- How to Get a Substring Before a Character Using substr() in C++?
- Use substr() in C++ to Print all Substrings of a Given String
- Print Sum of all Substrings of a String Representing a Number
- Minimum Value of all Substrings of a String Representing a Number
- Maximum Value of all Substrings of a String Representing a Number
- Points To Remember For Substr In C++
- Conclusion
- Frequently Asked Questions
- Test Your Skills: Quiz Time
- What Is Operator In C++?
- Types Of Operators In C++ With Examples
- What Are Arithmetic Operators In C++?
- What Are Assignment Operators In C++?
- What Are Relational Operators In C++?
- What Are Logical Operators In C++?
- What Are Bitwise Operators In C++?
- What Is Ternary/ Conditional Operator In C++?
- Miscellaneous Operators In C++
- Precedence & Associativity Of Operators In C++
- Conclusion
- Frequently Asked Questions
- Test Your Skills: Quiz Time
- What Is The New Operator In C++?
- Example To Understand New Operator In C++
- The Grammar Elements Of The New Operator In C++
- Storage Space Allocation
- How Does The C++ New Operator Works?
- What Happens When Enough Memory In The Program Is Not Available?
- Initializing Objects Allocated With New Operator In C++
- Lifetime Of Objects Allocated With The New Operator In C++
- What Is The Delete Operator In C++?
- Difference Between New And Delete Operator In C++
- Conclusion
- Frequently Asked Questions
- Test Your Skills: Quiz Time
- Types Of Overloading In C++
- What Is Operator Overloading In C++?
- How To Overload An Operator In C++?
- Overloadable & Non-overloadable Operators In C++
- Unary Operator Overloading In C++
- Binary Operator Overloading In C++
- Special Operator Overloading In C++
- Rules For Operator Overloading In C++
- Advantages And Disadvantages Of Operator Overloading In C++
- Function Overloading In C++
- What Is the Difference Between Operator Functions and Normal Functions?
- Conclusion
- Frequently Asked Questions
- Test Your Skills: Quiz Time
- What Are Operators In C++?
- Introduction To Logical Operators In C++
- Types Of Logical Operators In C++ With Example Program
- Logical AND (&&) Operator In C++
- Logical NOT(!) Operator In C++
- Logical Operator Precedence And Associativity In C++
- Relation Between Conditional Statements And Logical Operators In C++
- C++ Relational Operators
- Conclusion
- Frequently Asked Important Interview Questions:
- Test Your Skills: Quiz Time
- Different Type Of C++ Bitwise Operators
- C++ Bitwise AND Operator
- C++ Bitwise OR Operator
- C++ Bitwise XOR Operator
- Bitwise Left Shift Operator In C++
- Bitwise Right Shift Operator In C++
- Bitwise NOT Operator
- What Is The Meaning Of Set Bit In C++?
- What Does Clear Bit Mean?
- Conclusion
- Frequently Asked Questions
- Test Your Skills: Quiz Time
- Types of Comments in C++
- Single Line Comment In C++
- Multi-Line Comment In C++
- How Do Compilers Process Comments In C++?
- C- Style Comments In C++
- How To Use Comment In C++ For Debugging Purposes?
- When To Use Comments While Writing Codes?
- Why Do We Use Comments In Codes?
- Conclusion
- Frequently Asked Questions
- Test Your Skills: Quiz Time
- What Are Storage Classes In Cpp?
- What Is The Scope Of Variables?
- What Are Lifetime And Visibility Of Variables In C++?
- Types of Storage Classes in C++
- Automatic Storage Class In C++
- Register Storage Class In C++
- Static Storage Class In C++
- External Storage Class In C++
- Mutable Storage Class In C++
- Conclusion
- Frequently Asked Questions
- Test Your Skills: Quiz Time
- Decision Making Statements In C++
- Types Of Conditional Statements In C++
- If-Else Statement In C++
- If-Else-If Ladder Statement In C++
- Nested If Statements In C++
- Alternatives To Conditional If-Else In C++
- Switch Case Statement In C++
- Jump Statements & If-Else In C++
- Conclusion
- Frequently Asked Questions
- Test Your Skills: Quiz Time
- What Is A Switch Statement/ Switch Case In C++?
- Rules Of Switch Case In C++
- How Does Switch Case In C++ Work?
- The break Keyword In Switch Case C++
- The default Keyword In C++ Switch Case
- Switch Case Without Break And Default
- Advantages & Disadvantages of C++ Switch Case
- Conclusion
- Frequently Asked Questions
- Test Your Skills: Quiz Time
- What Is A For Loop In C++?
- Syntax Of For Loop In C++
- How Does A For Loop In C++ Work?
- Examples Of For Loop Program In C++
- Ranged Based For Loop In C++
- Nested For Loop In C++
- Infinite For Loop In C++
- Conclusion
- Frequently Asked Questions
- Test Your Skills: Quiz Time
- What Is A While Loop In C++?
- Parts Of The While Loop In C++
- C++ While Loop Program Example
- How Does A While Loop In C++ Work?
- What Is Pre-checking Process Or Entry-controlled Loop?
- When Are While Loops In C++ Useful?
- Example C++ While Loop Program
- What Are Nested While Loops In C++?
- Infinite While Loop In C++
- Alternatives To While Loop In C++
- Conclusion
- Frequently Asked Questions
- Test Your Skills: Quiz Time
- What Are Loops & Its Types In C++?
- What Is A Do-While Loop In C++?
- Do-While Loop Example In C++ To Print Numbers
- How Does A Do-While Loop In C++ Work?
- Various Components Of The Do-While Loop In C++
- Example 2: Adding User-Input Positive Numbers With Do-While Loop
- C++ Nested Do-While Loop
- C++ Infinitive Do-while Loop
- What is the Difference Between While Loop and Do While Loop in C++?
- When To Use A Do-While Loop?
- Conclusion
- Frequently Asked Questions
- Test Your Skills: Quiz Time
- What are 2D Vectors in C++?
- How to Declare 2D Vectors in C++
- How to Initialize a 2D Vector in C++?
- Creating a 2D Vector in C++ with User Input for Column & Row Size
- Methods for Traversing 2D Vectors in C++
- Interview Spotlight: 2D Vectors in FAANG Interviews
- Printing 2D Vector in C++ Using Nested Loops
- Example C++ Programs for Creating 2D Vectors
- How to Access & Modify 2D Vector Elements in C++?
- Adding Elements to 2D Vector Using push_back() Function
- Removing Elements from Vector in C++ Using pop_back() Function
- Did You Know? Real-World Outage: Crash Cause Linked to 2D Vector Usage
- Advantages of 2D Vectors Over Traditional Arrays
- Conclusion
- Frequently Asked Questions
- Test Your Skills: Quiz Time
- How To Print A Vector In C++ By Overloading Left Shift (<<) Operator?
- How To Print Vector In C++ Using Range-Based For-Loop?
- Print Vector In C++ With Comma Separator
- Printing Vector In C++ Using Indices (Square Brackets/ Double Brackets & at() Function)
- How To Print A Vector In C++ Using std::copy?
- How To Print A Vector In C++ Using for_each() Function?
- Printing C++ Vector Using The Lambda Function
- How To Print Vector In C++ Using Iterators?
- Conclusion
- Frequently Asked Questions
- Definition Of C++ Find In Vector
- Using The std::find() Function
- How Does find() In Vector C++ Function Work?
- Finding An Element By Custom Comparator Using std::find_if() Function
- Use std::find_if() With std::distance()
- Element Find In Vector C++ Using For Loop
- Using The find_if_not Function
- Find Elements With The Linear Search Approach
- Conclusion
- Frequently Asked Questions
- What Is Sort() Function In C++?
- Sort() Function In C++ From Standard Template Library
- Exceptions Of Sort() Function/ Algorithm In C++
- The Stable Sort() Function In C++
- Partial Sort() Function In C++
- Sorting In Ascending Order With Sort() Function In C++
- Sorting In Descending Order With Sort Function In C++
- Sorting In Desired Order With Custom Comparator Function & Sort Function In C++
- Sorting Elements In Desired Order Using Lambda Expression & Sort Function In C++
- Types of Sorting Algorithms In C++
- Advanced Sorting Algorithms In C++
- How Does the Sort() Function Algorithm Work In C++?
- Conclusion
- Frequently Asked Questions
- What Is Function Overloading In C++?
- Ways Of Function Overloading In C++
- Function Overloading In C++ Using Different Types Of Parameters
- Function Overloading In C++ With Different Number Of Parameters
- Function Overloading In C++ Using Different Sequence Of Parameters
- How Does Function Overloading In C++ Work?
- Rules Of Function Overloading In C++
- Why Is Function Overloading Used?
- Types Of Function Overloading Based On Time Of Resolution
- Causes Of Function Overloading In C++
- Ambiguity & Function Overloading In C++
- Advantages Of Function Overloading In C++
- Disadvantages Of Function Overloading In C++
- Operator Overloading In C++
- Function Overriding In C++
- Difference Between Function Overriding & Function Overloading In C++
- Conclusion
- Frequently Asked Questions
- What Is An Inline Function In C++?
- How To Define The Inline Function In C++?
- How Does Inline Function In C++ Work?
- The Need For An Inline Function In C++
- Can The Compiler Ignore/ Reject Inline Function In C++ Programs?
- Normal Function Vs. Inline Function In C++
- Classes & Inline Function In C++
- Understanding Inline, __inline, And __forceinline Functions In C++
- When To Use An Inline Function In C++?
- Advantages Of Inline Function In C++
- Disadvantages Of Inline Function In C++
- Why Not Use Macros Instead Of An Inline Function In C++?
- Conclusion
- Frequently Asked Questions
- Test Your Skills: Quiz Time
- What Is Static Data Member In C++?
- How To Declare Static Data Members In C++?
- How To Initialize/ Define Static Data Member In C++?
- Ways To Access A Static Data Member In C++
- What Are Static Member Functions In C++?
- Example Of Member Function & Static Data Member In C++
- Practical Applications Of Static Data Member In C++
- Conclusion
- Frequently Asked Questions
- What Is A Constant In C++?
- Ways To Define Constant In C++
- What Are Literals In C++?
- Pointer To A Constant In C++
- Constant Function Arguments In C++
- Constant Member Function Of Class In C++
- Constant Data Members In C++
- Object Constant In C++
- Conclusion
- Frequently Asked Questions(FAQ)
- What is the Friend Function in C++?
- Declaration of Friend Function in C++ with Example
- Characteristics of Friend Function in C++
- Types/ Ways to Implement Friend Function in C++
- Global Friend Function in C++ (Global Function as Friend Function )
- Member Function of Another Class as a Friend Function in C++
- Function Overloading Using Friend Function in C++
- Advantages & Disadvantages of Friend Function in C++
- Interview Spotlight: Friend Functions in Cognizant Interview
- What is a C++ Friend Class?
- A Function Friendly to Multiple Classes
- C++ Friend Class vs. Friend Function in C++
- Some Important Points About Friend Functions and Classes in C++
- Conclusion
- Frequently Asked Questions
- What Is Function Overriding In C++?
- The Working Mechanism Of Function Overriding In C++
- Real-Life Example Of Function Overriding In C++
- Accessing Overriding Function In C++
- Accessing Overridden Function In C++
- Function Call Binding With Class Objects | Function Overriding In C++
- Function Call Binding With Base Class Pointers | Function Overriding In C++
- Advantages Of Function Overriding In C++
- Variations In Function Overriding In C++
- Function Overloading In C++
- Function Overloading Vs Function Overriding In C++
- Conclusion
- Frequently Asked Questions
- Errors In C++
- What Is Exception Handling In C++?
- Exception Handling In C++ Program Example
- C++ Exception Handling: Basic Keywords
- The Need For C++ Exception Handling
- C++ Standard Exceptions
- C++ Exception Classes
- User-Defined Exceptions In C++
- Advantages & Disadvantages Of C++ Exception Handling
- Conclusion
- Frequently Asked Questions
- What Are Templates In C++ & How Do They Work?
- Types Of Templates In C++
- What Are Function Templates In C++?
- C++ Template Functions With Multiple Parameters
- C++ Template Function Overloading
- What Are Class Templates In C++?
- Defining A Class Member Outside C++ Template Class
- C++ Template Class With Multiple Parameters
- What Is C++ Template Specialization?
- How To Specify Default Arguments For Templates In C++?
- Advantages Of C++ Templates
- Disadvantages Of C++ Templates
- Difference Between Function Overloading And Templates In C++
- Conclusion
- Frequently Asked Questions
- Structure
- Structure Declaration
- Initialization of Structure
- Copying and Comparing Structures
- Array of Structures
- Nested Structures
- Pointer to a Structure
- Structure as Function Argument
- Self Referential Structures
- Class
- Object Declaration
- Accessing Class Members
- Similarities between Structure and Class
- Which One Should You Choose?
- Key Difference Between a Structure and Class
- Summing Up
- Test Your Skills: Quiz Time
- What Is A Class And Object In C++?
- What Is An Object In C++?
- How To Create A Class & Object In C++? With Example
- Interview Spotlight: Classes & Objects In Adobe & Pixar Interviews
- Access Modifiers & Class/ Object In C++
- Member Functions Of A Class In C++
- How To Access Data Members And Member Functions?
- Significance Of Class & Object In C++
- Did You Know? The Concept of Classes & Object Powers Major Apps
- What Are Constructors In C++ & Its Types?
- What Is A Destructor Of Class In C++?
- An Array Of Objects In C++
- Object In C++ As Function Arguments
- The this (->) Pointer & Classes In C++
- The Need For Semicolons At The End Of A Class In C++
- Conclusion
- Frequently Asked Questions
- What Are Static Members In C++?
- Static Member Functions in C++
- Ways To Call Static Member Function In C++
- Properties Of Static Member Function In C++
- Need Of Static Member Functions In C++
- Regular Member Function Vs. Static Member Function In C++
- Limitations Of Static Member Functions In C++
- Conclusion
- Frequently Asked Questions
- What Is Constructor In C++?
- Characteristics Of A Constructor In C++
- Types Of Constructors In C++
- Default Constructor In C++
- Parameterized Constructor In C++
- Copy Constructor In C++
- Dynamic Constructor In C++
- Benefits Of Using Constructor In C++
- How Does Constructor In C++ Differ From Normal Member Function?
- Constructor Overloading In C++
- Constructor For Array Of Objects In C++
- Constructor In C++ With Default Arguments
- Initializer List For Constructor In C++
- Dynamic Initialization Using Constructor In C++
- Conclusion
- Frequently Asked Questions
- What Is A Constructor In C++?
- What Is Constructor Overloading In C++?
- Dеclaration Of Constructor Ovеrloading In C++
- Condition For Constructor Overloading In C++
- How Constructor Ovеrloading In C++ Works?
- Examples Of Constructor Overloading In C++
- Lеgal & Illеgal Constructor Ovеrloading In C++
- Types Of Constructors In C++
- Characteristics Of Constructors In C++
- Advantage Of Constructor Overloading In C++
- Disadvantage Of Constructor Overloading In C++
- Conclusion
- Frеquеntly Askеd Quеstions
- What Is A Destructor In C++?
- Rules For Defining A Destructor In C++
- When Is A Destructor in C++ Called?
- Order Of Destruction In C++
- Default Destructor & User-Defined Destructor In C++
- Virtual Destructor In C++
- Pure Virtual Destructor In C++
- Key Properties Of Destructor In C++ You Must Know
- Explicit Destructor Calls In C++
- Destructor Overloading In C++
- Difference Between Normal Member Function & Destructor In C++
- Important Uses Of Destructor In C++
- Conclusion
- Frequently Asked Questions
- What Is A Constructor In C++?
- What Is A Destructor In C++?
- Difference Between Constructor And Destructor In C++
- Constructor In C++ | A Brief Explanation
- Destructor In C++ | A Brief Explanation
- Difference Between Constructor And Destructor In C++ Explained
- Order Of Calling Constructor And Destructor In C++ Classes
- Conclusion
- Frequently Asked Questions
- Test Your Skills: Quiz Time
- What Is Type Conversion In C++?
- What Is Type Casting In C++?
- Types Of Type Conversion In C++
- Implicit Type Conversion (Coercion) In C++
- Explicit Type Conversion (Casting) In C++
- Advantages Of Type Conversion In C++
- Disadvantages Of Type Conversion In C++
- Difference Between Type Casting & Type Conversion In C++
- Application Of Type Casting In C++
- Conclusion
- Frequently Asked Questions
- What Is A Copy Constructor In C++?
- Characteristics Of Copy Constructors In C++
- Types Of Copy Constructors In C++
- When Do We Call The Copy Constructor In C++?
- When Is A User-Defined Copy Constructor Needed In C++?
- Types Of Constructor Copies In C++
- Can We Make The Copy Constructor In C++ Private?
- Assignment Operator Vs Copy Constructor In C++
- Example Of Class Where A Copy Constructor Is Essential
- Uses Of Copy Constructors In C++
- Conclusion
- Frequently Asked Questions
- Why Do You Need Object-Oriented Programming (OOP) In C++?
- OOPs Concepts In C++ With Examples
- The Class OOPs Concept In C++
- The Object OOPs Concept In C++
- The Inheritance OOPs Concept In C++
- Polymorphism OOPs Concept In C++
- Abstraction OOPs Concept In C++
- Encapsulation OOPs Concept In C++
- Other Features Of OOPs In C++
- Benefits Of OOP In C++ Over Procedural-Oriented Programming
- Disadvantages Of OOPS Concept In C++
- Why Is C++ A Partial OOP Language?
- Conclusion
- Frequently Asked Questions
- Introduction To Abstraction In C++
- Types Of Abstraction In C++
- What Is Data Abstraction In C++?
- Understanding Data Abstraction In C++ Using Real Life Example
- Ways Of Achieving Data Abstraction In C++
- What Is An Abstract Class?
- Advantages Of Data Abstraction In C++
- Use Cases Of Data Abstraction In C++
- Encapsulation Vs. Abstraction In C++
- Conclusion
- Frequently Asked Questions
- What Is Encapsulation In C++?
- How Does Encapsulation Work In C++?
- Types Of Encapsulation In C++
- Why Do We Need Encapsulation In C++?
- Implementation Of Encapsulation In C++
- Access Specifiers & Encapsulation In C++
- Role Of Access Specifiers In Encapsulation In C++
- Member Functions & Encapsulation In C++
- Data Hiding & Encapsulation In C++
- Features Of Encapsulation In C++
- Advantages & Disadvantages Of Encapsulation In C++
- Difference Between Abstraction and Encapsulation In C++
- Conclusion
- Frequently Asked Questions
- What Is Inheritance In C++?
- What Are Child And Parent Classes?
- Syntax And Structure Of Inheritance In C++
- Implementing Inheritance In C++
- Importance Of Inheritance In C++
- Types Of Inheritance In C++
- Visibility Modes Of Inheritance In C++
- Access Modifiers & Inheritance In C++
- How To Make A Private Member Inheritable?
- Member Function Overriding In Inheritance In C++
- The Diamond Problem | Inheritance In C++ & Ambiguity
- Ways To Avoid Ambiguity Inheritance In C++
- Why & When To Use Inheritance In C++?
- Advantages Of Inheritance In C++
- The Disadvantages Of Inheritance In C++
- Conclusion
- Frequently Asked Questions
- What Is Hybrid Inheritance In C++?
- Importance Of Hybrid Inheritance In Object Oriented Programming
- Example Of Hybrid Inheritance In C++: Using Single and Multiple Inheritance
- Example Of Hybrid Inheritance In C++: Using Multilevel and Hierarchical Inheritance
- Real-World Applications Of Hybrid Inheritance In C++
- Conclusion
- Frequently Asked Questions
- What Is Multiple Inheritance In C++?
- Examples Of Multiple Inheritance In C++
- Ambiguity Problem In Multiple Inheritance In C++
- Ambiguity Resolution In Multiple Inheritance In C++
- The Diamond Problem In Multiple Inheritance In C++
- Visibility Modes In Multiple Inheritance In C++
- Advantages & Disadvantages Of Multiple Inheritance In C++
- Multiple Inheritance Vs. Multilevel Inheritance In C++
- Conclusion
- Frequently Asked Questions
- What Is Multilevel Inheritance In C++?
- Block Diagram For Multilevel Inheritance In C++
- Multilevel Inheritance In C++ Example
- Constructor & Multilevel Inheritance In C++
- Use Cases Of Multilevel Inheritance In C++
- Multiple Vs Multilevel Inheritance In C++
- Advantages & Disadvantages Of Multilevel Inheritance In C++
- Conclusion
- Frequently Asked Questions
- What Is Hierarchical Inheritance In C++?
- Example 1: Hierarchical Inheritance In C++
- Example 2: Hierarchical Inheritance In C++
- Impact of Visibility Modes In Hierarchical Inheritance In C++
- Advantages And Disadvantages Of Hierarchical Inheritance In C++
- Use Cases Of Hierarchical Inheritance In C++
- Conclusion
- Frequently Asked Questions
- What Are Access Specifiers In C++?
- Types Of Access Specifiers In C++
- Public Access Specifiers In C++
- Private Access Specifier In C++
- Protected Access Specifier In C++
- The Need For Access Specifiers In C++
- Combined Example For All Access Specifiers In C++
- Best Practices For Using Access Specifiers In C++
- Why Can't Private Members Be Accessed From Outside A Class?
- Conclusion
- Frequently Asked Questions
- What Is The Diamond Problem In C++?
- Example Of The Diamond Problem In C++
- Resolution Of The Diamond Problem In C++
- Virtual Inheritance To Resolve Diamond Problem In C++
- Scope Resolution Operator To Resolve Diamond Problem In C++
- Conclusion
- Frequently Asked Questions
Pointer To Object In C++ | Declare, Usage & More (+Code Examples)
Pointers are a fundamental concept in C++, enabling programmers to manipulate objects indirectly (using the address for access) and dynamically allocate memory. In that, pointers to objects in C++ classes, provide powerful capabilities for memory management, allowing developers to allocate and deallocate memory dynamically. In this article, we will explore the concept of pointers to objects, their advantages, and best practices for using them effectively in C++ programming language.
Understanding Pointers In C++

In C++, a pointer is a variable that holds the memory address of another variable. Pointers allow for efficient memory utilization, as they enable dynamic memory allocation, deallocation, and indirect access to objects/ data. When declaring a pointer, you must specify the data type of the variable it will be pointing to. For example, int* ptr declares a pointer to an integer variable.
Syntax For Pointer Variable Declaration In C++
datatype *var_name;
int *ptr; // Ptr can direct attention to an address that contains int data.
Let's look at an example to understand the implementation of pointer variables in C++ programming.
Code Example:
#include
int main() {
int x = 42;
int* ptr = &x;
std::cout << "The value of x is: " << x << std::endl;
std::cout << "The address of x is: " << &x << std::endl;
std::cout << "The value of ptr is: " << ptr << std::endl;
std::cout << "The value pointed to by ptr is: " << *ptr << std::endl;
*ptr = 100;
std::cout << "The new value of x is: " << x << std::endl;
return 0;
}
I2luY2x1ZGUgPGlvc3RyZWFtPgoKaW50IG1haW4oKSB7CmludCB4ID0gNDI7CmludCogcHRyID0gJng7CgpzdGQ6OmNvdXQgPDwgIlRoZSB2YWx1ZSBvZiB4IGlzOiAiIDw8IHggPDwgc3RkOjplbmRsOwpzdGQ6OmNvdXQgPDwgIlRoZSBhZGRyZXNzIG9mIHggaXM6ICIgPDwgJnggPDwgc3RkOjplbmRsOwpzdGQ6OmNvdXQgPDwgIlRoZSB2YWx1ZSBvZiBwdHIgaXM6ICIgPDwgcHRyIDw8IHN0ZDo6ZW5kbDsKc3RkOjpjb3V0IDw8ICJUaGUgdmFsdWUgcG9pbnRlZCB0byBieSBwdHIgaXM6ICIgPDwgKnB0ciA8PCBzdGQ6OmVuZGw7CgoqcHRyID0gMTAwOwoKc3RkOjpjb3V0IDw8ICJUaGUgbmV3IHZhbHVlIG9mIHggaXM6ICIgPDwgeCA8PCBzdGQ6OmVuZGw7CgpyZXR1cm4gMDsKfQ==
Output:
The value of x is: 42
The address of x is: 0x7ffef459dc14
The value of ptr is: 0x7ffef459dc14
The value pointed to by ptr is: 42
The new value of x is: 100
Explanation:
In this example, we first include the <iostream> header for input/ output operations.
- Inside the main() function, we declare and initialize the integer variable x with a value of 42.
- Then, we declare a pointer variable ptr and assign it the address of variable x, using the address-of operator (&).
- After that, we use the std::cout commands to print the value of variable x (direct access), the value of the ptr/ address of x twice (first using &x and second using ptr directly), and the value pointed to by ptr using the pointer notation (*ptr).
- Next, we use the dereference operator (*) to modify the value being pointed to, by assigning the value 100 to ptr. The output shows that the modification was successful as we print the new value.
- Lastly, the main() function returns 0, indicating the successful execution of the program.
This C++ program shows how pointers can be used to access a variable's memory address and change its value indirectly.
For more, read: Pointers in C++ | A Roadmap To All Types Of Pointers With Examples
Pointer Reference Guide
|
Syntax |
Meaning |
|
int *p |
A pointer p is declared. |
|
p = new int |
Creates a dynamic memory integer variable and assigns its address to p. |
|
p = new int[7] |
Inserts the address of the first index of a dynamic array of size 7 in p. |
|
p = &var |
Pointer stores directly to the var variable. |
|
*p |
Reads the object's value that p points to |
|
*p = 7 |
Changes the object’s value that p points to |
|
p |
Reads the object's memory location that p corresponds to |
What Is Pointer To Object In C++?

A pointer to an object in C++ is a variable that holds the memory address of an object. It allows indirect access to the object, providing a way to manipulate and interact with the object dynamically. Pointers to objects are particularly useful when dealing with dynamically allocated memory, enabling flexible memory management and dynamic object creation.
When we create an object for a class, it occupies a specific memory location. Here, a pointer to object in C++ class stores the memory address of that object rather than the object itself. These pointers allow programmers to access and modify the object indirectly, without creating its copies. This is especially useful for efficient memory usage and passing objects to functions by reference. Below is an example that illustrates the concept of a pointer to object in C++.
Code Example:
#include
class MyClass {
public:
void myFunction() {
std::cout << "Hello from MyClass!" << std::endl;
}
};
int main() {
MyClass obj; // Create an object of MyClass
MyClass* ptr = &obj; // Create a pointer to the object
ptr->myFunction(); // Access functions using the pointer
return 0;
}
I2luY2x1ZGUgPGlvc3RyZWFtPgoKY2xhc3MgTXlDbGFzcyB7CnB1YmxpYzoKdm9pZCBteUZ1bmN0aW9uKCkgewpzdGQ6OmNvdXQgPDwgIkhlbGxvIGZyb20gTXlDbGFzcyEiIDw8IHN0ZDo6ZW5kbDsKfQp9OwoKaW50IG1haW4oKSB7Ck15Q2xhc3Mgb2JqOyAvLyBDcmVhdGUgYW4gb2JqZWN0IG9mIE15Q2xhc3MKTXlDbGFzcyogcHRyID0gJm9iajsgLy8gQ3JlYXRlIGEgcG9pbnRlciB0byB0aGUgb2JqZWN0CgpwdHItPm15RnVuY3Rpb24oKTsgLy8gQWNjZXNzIGZ1bmN0aW9ucyB1c2luZyB0aGUgcG9pbnRlcgoKcmV0dXJuIDA7Cn0=
Output:
Hello from MyClass!
Explanation:
In the example above,
- We define a class named MyClass, containing a public member function myFunction() that uses std::cout to print a message to the console.
- In the main() function, we create an instance/ object of MyClass named obj.
- Then, we declare a pointer ptr of type MyClass* and assign it the memory address of obj using the address-of operator (&).
- After that, we show how we can use this pointer along with the arrow operator/ 'this' pointer (->) to access the member function myFunction() of the obj object.
- As shown in the output, even though the myFunction() is a part of the class, we can access it using a pointer to object of that C++ class.
Pointers to objects provide flexibility in scenarios where objects need to be created dynamically, their lifetimes extend beyond a specific scope, or when objects are accessed indirectly for efficiency purposes. They are commonly used in data structures, dynamic memory allocation, object-oriented programming, and other advanced programming techniques.
Declaration And Use Of Object Pointers In C++
The process for creating object pointers is similar to that of ordinary pointers, i.e., appending it to the name of the pointer type. However, note that we use the arrow operator (->) instead of the dot operator when utilizing an object pointer to access members of an already-defined class.
The example program below illustrates the use of object pointers in C++.
Code Example:
#include
class Date {
int day, month, year;
public:
Date() {
day = month = year = 0;
}
void setData(int d, int m, int y) {
day = d;
month = m;
year = y;
}
void printData() {
std::cout << "The date is " << day << "/" << month << "/" << year << std::endl;
}
};
int main() {
Date D1, *dptr;
std::cout << "Initializing data members using the object with values 1, 1, and 2000\n";
D1.setData(1, 1, 2000);
std::cout << "Printing members using the object: ";
D1.printData();
dptr = &D1;
std::cout << "Printing members using the object pointer: ";
dptr->printData();
std::cout << "\nInitializing data members using the object pointer, with values 31, 12, and 2023\n";
dptr->setData(31, 12, 2023);
std::cout << "Printing members using the object: ";
D1.printData();
std::cout << "Printing members using the object pointer: ";
dptr->printData();
return 0;
}
I2luY2x1ZGUgPGlvc3RyZWFtPgoKY2xhc3MgRGF0ZSB7CmludCBkYXksIG1vbnRoLCB5ZWFyOwoKcHVibGljOgpEYXRlKCkgewpkYXkgPSBtb250aCA9IHllYXIgPSAwOwp9Cgp2b2lkIHNldERhdGEoaW50IGQsIGludCBtLCBpbnQgeSkgewpkYXkgPSBkOwptb250aCA9IG07CnllYXIgPSB5Owp9Cgp2b2lkIHByaW50RGF0YSgpIHsKc3RkOjpjb3V0IDw8ICJUaGUgZGF0ZSBpcyAiIDw8IGRheSA8PCAiLyIgPDwgbW9udGggPDwgIi8iIDw8IHllYXIgPDwgc3RkOjplbmRsOwp9Cn07CgppbnQgbWFpbigpIHsKRGF0ZSBEMSwgKmRwdHI7CgpzdGQ6OmNvdXQgPDwgIkluaXRpYWxpemluZyBkYXRhIG1lbWJlcnMgdXNpbmcgdGhlIG9iamVjdCB3aXRoIHZhbHVlcyAxLCAxLCBhbmQgMjAwMFxuIjsKRDEuc2V0RGF0YSgxLCAxLCAyMDAwKTsKCnN0ZDo6Y291dCA8PCAiUHJpbnRpbmcgbWVtYmVycyB1c2luZyB0aGUgb2JqZWN0OiAiOwpEMS5wcmludERhdGEoKTsKCmRwdHIgPSAmRDE7CgpzdGQ6OmNvdXQgPDwgIlByaW50aW5nIG1lbWJlcnMgdXNpbmcgdGhlIG9iamVjdCBwb2ludGVyOiAiOwpkcHRyLT5wcmludERhdGEoKTsKCnN0ZDo6Y291dCA8PCAiXG5Jbml0aWFsaXppbmcgZGF0YSBtZW1iZXJzIHVzaW5nIHRoZSBvYmplY3QgcG9pbnRlciwgd2l0aCB2YWx1ZXMgMzEsIDEyLCBhbmQgMjAyM1xuIjsKZHB0ci0+c2V0RGF0YSgzMSwgMTIsIDIwMjMpOwoKc3RkOjpjb3V0IDw8ICJQcmludGluZyBtZW1iZXJzIHVzaW5nIHRoZSBvYmplY3Q6ICI7CkQxLnByaW50RGF0YSgpOwoKc3RkOjpjb3V0IDw8ICJQcmludGluZyBtZW1iZXJzIHVzaW5nIHRoZSBvYmplY3QgcG9pbnRlcjogIjsKZHB0ci0+cHJpbnREYXRhKCk7CgpyZXR1cm4gMDsKfQ==
Output:
Initializing data members using the object with values 1, 1, and 2000
Printing members using the object: The date is 1/1/2000
Printing members using the object pointer: The date is 1/1/2000Initializing data members using the object pointer, with values 31, 12, and 2023
Printing members using the object: The date is 31/12/2023
Printing members using the object pointer: The date is 31/12/2023
Explanation:
In the above code example-
- We start by defining a class Date with three private integer data members: day, month, and year.
- Then, we use the public access specifier and create a default constructor, Date(), that initializes the day, month, and year to 0.
- We then define a member function setData() to set the values of day, month, and year data members using the parameters d, m, and y. This allows us to change the date information later.
- Next, we define a printData() function that outputs the date in a day/month/year format using the std::cout command.
- In the main() function, we create an object of Date class, D1, and a pointer dptr of type Date (i.e., it will point to object of Date class).
- First, we use the dot operator to call the setData() function on object D1 to initialize its data members with values 1, 1, and 2000, respectively.
-
We then print these values using the printData() function, which outputs the date to the console. (i.e., D1.printData())
- Next, we assign the address of D1 to the pointer dptr using the address of operator(&). This will make the pointer dptr point to the same memory location as D1.
- After that, we call the printData() function using the pointer to the object, dptr, and arrow operator, i.e., dptr->printData().
- Then, we update the date using the pointer dptr by calling the setData() function with values 31, 12, and 2023. This modifies the values in the object D1 because both dptr and D1 refer to the same instance.
- Finally, we print the updated date by calling the printData() function twice, once by using the object name (D1) and once by using the pointer to the object (dptr).
- As seen in the output, both the calls to the function print the same value, showing modifications made using pointers to objects in C++ classes, modify the object.
This program shows C++ users how to declare a pointer to an object, use it, and access member functions. Aside from being presented as functions that take an object pointer in their implicit arguments, the said base pointer could also be utilized to reach the members and procedures of the object.
Advantages Of Pointer To Object In C++
The advantages of using a pointer to an object in C++ are as follows:
- Pointers grant us the power to dynamically distribute storage, enabling object creation at execution and releasing memory when it is not needed. It is especially useful in situations where either the generation of objects is dependent on user input, there are other runtime conditions, or knowledge of an object's size at compile time is lacking.
- When compared to passing by value, pointers to objects allow us to pass objects to functions by reference, which can be more effective. When we provide an object by value, a copy of the item is made, which for large objects can be time and memory-consuming. It is more effective to pass an object by reference, which merely passes the item's address.
- Incorporating polymorphism into our coding is a viable option, as instances of derived classes can be pointed to by including pointers from their base equivalents. As long as they share a base class, we can develop code that interacts with objects of various sorts.
- Smart pointers offer ownership semantics for objects that are allocated dynamically. Objects' lifespan can be governed using these effective programming tools to ensure they are properly disposed of when no longer necessary. This guarantees accurate deallocation and prevents any unintended consequences from the object's persistence.
- Pointers to objects are essential for implementing dynamic data structures like linked lists, trees, graphs, and hash tables. These structures rely on objects that are created and connected at runtime, where pointers manage the relationships between objects.
- Multiple pointers can reference the same object in memory, allowing us to share objects across different parts of a program without duplicating data. This is useful in scenarios where the same data needs to be accessed or modified by different modules or functions.
Pointer To Objects In C++ With Arrow Operator
We've already seen the use of the arrow operator/ 'this' pointer in the examples above. In this section, we will discuss the use of this operator to access an object's members referenced by a pointer in detail.
- We should use the arrow operator instead of the (.) dot operator in cases where we possess an object pointer.
- This is because the arrow operator is a viable means to access members belonging to that specific object.
Also note that the arrow operator is a combination of the dereference operator (*) and the dot operator (.). It is used to access the member of the object that the pointer points to and dereference the pointer.
Syntax:
(pointer_name)->(variable_name)
Below is an example program that shows how to use the C++ arrow operator with pointers to objects.
Code Example:
#include
class MyClass {
public:
int x;
void print() {
std::cout << "The value of x is: " << x << std::endl;
}
};
int main() {
MyClass obj;
obj.x = 42;
MyClass* ptr = &obj;
ptr->print(); // Accessing object using pointer
return 0;
}
I2luY2x1ZGUgPGlvc3RyZWFtPgoKY2xhc3MgTXlDbGFzcyB7CnB1YmxpYzoKaW50IHg7Cgp2b2lkIHByaW50KCkgewpzdGQ6OmNvdXQgPDwgIlRoZSB2YWx1ZSBvZiB4IGlzOiAiIDw8IHggPDwgc3RkOjplbmRsOwp9Cn07CgppbnQgbWFpbigpIHsKTXlDbGFzcyBvYmo7Cm9iai54ID0gNDI7CgpNeUNsYXNzKiBwdHIgPSAmb2JqOwpwdHItPnByaW50KCk7IC8vIEFjY2Vzc2luZyBvYmplY3QgdXNpbmcgcG9pbnRlcgoKcmV0dXJuIDA7Cn0=
Output:
The value of x is: 42
Explanation:
In this example, we define a class named MyClass with a public integer member variable x and a public member function print().
- The print() member function outputs the value of x using the std::cout command.
- In the main() function, we create an object obj of type MyClass.
- Next, we assign the value 42 to the member variable x of the object obj.
- We then declare a pointer ptr of type MyClass* and assign it the address of obj using the address-of-operator (&).
- Finally, we use the pointer ptr to call the print() function by using the arrow operator (->), which prints the value of x through the pointer.
This program shows how to use the arrow operator with object references and pointers to objects in C++ classes. In instances where simple functions necessitate the input of an object pointer as a parameter, one may utilize the arrow operator to gain access to both methods and members of the object.
An Array Of Objects Using Pointers In C++

A group of related data objects stored in contiguous memory locations can be accessed randomly using an array's indices in C++ or any other programming language. Arrays can be used to store elementary data types such as int, float, double, or char.
An array of objects:
No memory or storage is allocated when a class is defined; only the object's specification is defined. You must build objects in order to use the data and access the class's defined functions.
Syntax:
ClassName ObjectName[number of objects];
Code Example:
#include
#include
using namespace std;
class Person {
public:
string name;
int age;
};
int main() {
Person* people = new Person[3];
// Initialize array elements
people[0].name = "Jia";
people[0].age = 25;
people[1].name = "Maira";
people[1].age = 30;
people[2].name = "Bhaskar";
people[2].age = 35;
// Print array elements
for (int i = 0; i < 3; i++) {
cout << people[i].name << " is " << people[i].age << " years old." << endl;
}
// Free allocated memory
delete[] people;
return 0;
}
I2luY2x1ZGUgPGlvc3RyZWFtPgojaW5jbHVkZSA8c3RyaW5nPgoKdXNpbmcgbmFtZXNwYWNlIHN0ZDsKCmNsYXNzIFBlcnNvbiB7CnB1YmxpYzoKc3RyaW5nIG5hbWU7CmludCBhZ2U7Cn07CgppbnQgbWFpbigpIHsKUGVyc29uKiBwZW9wbGUgPSBuZXcgUGVyc29uWzNdOwoKLy8gSW5pdGlhbGl6ZSBhcnJheSBlbGVtZW50cwpwZW9wbGVbMF0ubmFtZSA9ICJKaWEiOwpwZW9wbGVbMF0uYWdlID0gMjU7CnBlb3BsZVsxXS5uYW1lID0gIk1haXJhIjsKcGVvcGxlWzFdLmFnZSA9IDMwOwpwZW9wbGVbMl0ubmFtZSA9ICJCaGFza2FyIjsKcGVvcGxlWzJdLmFnZSA9IDM1OwoKLy8gUHJpbnQgYXJyYXkgZWxlbWVudHMKZm9yIChpbnQgaSA9IDA7IGkgPCAzOyBpKyspIHsKY291dCA8PCBwZW9wbGVbaV0ubmFtZSA8PCAiIGlzICIgPDwgcGVvcGxlW2ldLmFnZSA8PCAiIHllYXJzIG9sZC4iIDw8IGVuZGw7Cn0KCi8vIEZyZWUgYWxsb2NhdGVkIG1lbW9yeQpkZWxldGVbXSBwZW9wbGU7CgpyZXR1cm4gMDsKfQ==
Output:
Jia is 25 years old.
Maira is 30 years old.
Bhaskar is 35 years old.
Explanation:
- In this program, we define a class named Person with two public data members: name (of type string) and age (of type int).
- Inside the main() function, we dynamically allocate an array of Person objects using the new operator and assign it to the pointer people.
- We then initialize the elements of the array individually, using index values and dot operator:
- For the first Person object (people[0]), we set the name to "Jia" and the age to 25.
- For the second Person object (people[1]), we set the name to "Maira" and the age to 30.
- For the third Person object (people[2]), we set the name to "Bhaskar" and the age to 35.
- Finally, we print the array elements by iterating through it using a for loop and dot notation to access the name and age member variables of each object.
- In order to prevent memory leaks, we then release the memory allocated by new using the delete[] operator.
Base Class Pointer For Derived Class Object In C++

In C++, a pointer to a base type class object may point to an object of a derived class. This is conceivable as a result of derived classes, which are classes that borrow characteristics from their base classes. It is possible to employ both a reference pointing towards an object of either the base class or derived class as they are compatible in type and offer several benefits. There exist diverse applications for working with these pointers to objects that belong to different classes.
Notes:
- A base class pointer referring to a derived class is a pointer to a derived class, but it will retain its aspect.
- The pointer of the base class is endowed with the ability to modify its distinct functions and variables while simultaneously being directed toward an object that originates from a subclass.
Here is a program to show a base class pointer can be used as the pointer to object of derived class.
Code Example:
#include
using namespace std;
class Shape {
public:
virtual void display() {
cout << "This is a shape." << endl;
}
};
class Rectangle : public Shape {
public:
void display() override {
cout << "This is a rectangle." << endl;
}
};
class Circle : public Shape {
public:
void display() override {
cout << "This is a circle." << endl;
}
};
int main() {
Shape* s; // Declare a base class pointer
Rectangle r; // Create a derived class object
Circle c; // Create another derived class object
s = &r; // Point the base class pointer to the rectangle object
s->display(); // Call the display() function of the derived class
s = &c; // Point the base class pointer to the circle object
s->display(); // Call the display() function of the derived class
return 0;
}
I2luY2x1ZGUgPGlvc3RyZWFtPgoKdXNpbmcgbmFtZXNwYWNlIHN0ZDsKCmNsYXNzIFNoYXBlIHsKcHVibGljOgp2aXJ0dWFsIHZvaWQgZGlzcGxheSgpIHsKY291dCA8PCAiVGhpcyBpcyBhIHNoYXBlLiIgPDwgZW5kbDsKfQp9OwoKY2xhc3MgUmVjdGFuZ2xlIDogcHVibGljIFNoYXBlIHsKcHVibGljOgp2b2lkIGRpc3BsYXkoKSBvdmVycmlkZSB7CmNvdXQgPDwgIlRoaXMgaXMgYSByZWN0YW5nbGUuIiA8PCBlbmRsOwp9Cn07CgpjbGFzcyBDaXJjbGUgOiBwdWJsaWMgU2hhcGUgewpwdWJsaWM6CnZvaWQgZGlzcGxheSgpIG92ZXJyaWRlIHsKY291dCA8PCAiVGhpcyBpcyBhIGNpcmNsZS4iIDw8IGVuZGw7Cn0KfTsKCmludCBtYWluKCkgewpTaGFwZSogczsgLy8gRGVjbGFyZSBhIGJhc2UgY2xhc3MgcG9pbnRlcgpSZWN0YW5nbGUgcjsgLy8gQ3JlYXRlIGEgZGVyaXZlZCBjbGFzcyBvYmplY3QKQ2lyY2xlIGM7IC8vIENyZWF0ZSBhbm90aGVyIGRlcml2ZWQgY2xhc3Mgb2JqZWN0CgpzID0gJnI7IC8vIFBvaW50IHRoZSBiYXNlIGNsYXNzIHBvaW50ZXIgdG8gdGhlIHJlY3RhbmdsZSBvYmplY3QKcy0+ZGlzcGxheSgpOyAvLyBDYWxsIHRoZSBkaXNwbGF5KCkgZnVuY3Rpb24gb2YgdGhlIGRlcml2ZWQgY2xhc3MKCnMgPSAmYzsgLy8gUG9pbnQgdGhlIGJhc2UgY2xhc3MgcG9pbnRlciB0byB0aGUgY2lyY2xlIG9iamVjdApzLT5kaXNwbGF5KCk7IC8vIENhbGwgdGhlIGRpc3BsYXkoKSBmdW5jdGlvbiBvZiB0aGUgZGVyaXZlZCBjbGFzcwoKcmV0dXJuIDA7Cn0=
Output:
This is a rectangle.
This is a circle.
Explanation:
In this program, we first include the standard Input/Output header file.
- We then create a base class named Shape with a public virtual function named display(). It prints a message to the console using the cout statement.
- Next, we create another class named Rectangle, which inherits the base class Shape and overrides the display() function. It prints a different method than the function from the base class, overriding it with its own definition.
- Then we create another class named Circle, which inherits the base class Shape and overrides the display() function, just like the Rectangle class.
- In the main() function, we declare the Shape class pointer (Shape*) and create objects r and c for the Rectangle and Circle classes, respectively.
- We then call the display() function of the derived class using the arrow operator (->) and point the base class pointer s to the object r.
- We will print an output to the console when the display() function is implemented within an instance of class Rectangle.
- Then we once again call the display() function of the derived class after we have pointed the base class pointer s to the object c.
- This time, it will invoke the Circle class' display() method and print the output to the console.
We can implement polymorphism in our program and create more adaptable, reusable code by employing a base class reference to point to derived class objects.
Conclusion
Within C++, the pointer variable is utilized to contain and manage the memory addresses of objects, permitting indirect entry into said objects. This approach enables us with a means of accessing objects outside their immediate scope without any difficulty or complication by using pointers instead.
When employing pointers to objects, we must take responsibility for memory management. Within the context of C++, pointers act as variables capable of storing and, more vitally, directing toward another variable's address. It is vital to note that these entities bear an identical data type in comparison with regular variables.
One may employ pointers to instantiate memory allocation and deallocation dynamically, create as well as alter dynamic data structures, and simulate call-by-reference functionality. Through the memory location it stores, a pointer indirectly references a value, and a reference enables us to operate an object using a pointer without having to manage memory manually.
Frequently Asked Questions
Q. How do you declare a pointer to an object in C++?
We use a particular syntax for declaring object pointers in the context of C++.
Syntax:
class-name *object-pointer-name
Here, the pointer variable is declared with the * operator.
Q. How can we write a program to illustrate pointers in C++?
Here is an example of how to write a program to show pointers in C++.
Code Example:
#include
void swap(int* a, int* b) {
int temp = *a;
*a = *b;
*b = temp;
}
int main() {
int x = 10;
int y = 20;
std::cout << "Before swapping: x = " << x << ", y = " << y << std::endl;
swap(&x, &y);
std::cout << "After swapping: x = " << x << ", y = " << y << std::endl;
return 0;
}
I2luY2x1ZGUgPGlvc3RyZWFtPgoKdm9pZCBzd2FwKGludCogYSwgaW50KiBiKSB7CmludCB0ZW1wID0gKmE7CiphID0gKmI7CipiID0gdGVtcDsKfQoKaW50IG1haW4oKSB7CmludCB4ID0gMTA7CmludCB5ID0gMjA7CgpzdGQ6OmNvdXQgPDwgIkJlZm9yZSBzd2FwcGluZzogeCA9ICIgPDwgeCA8PCAiLCB5ID0gIiA8PCB5IDw8IHN0ZDo6ZW5kbDsKc3dhcCgmeCwgJnkpOwpzdGQ6OmNvdXQgPDwgIkFmdGVyIHN3YXBwaW5nOiB4ID0gIiA8PCB4IDw8ICIsIHkgPSAiIDw8IHkgPDwgc3RkOjplbmRsOwoKcmV0dXJuIDA7Cn0=
Output:
Before swapping: x = 10, y = 20
After swapping: x = 20, y = 10
Explanation:
This program describes the function swap, which swaps the values pointed to by two integer pointers as arguments using a temporary variable.
- The program declares and initializes the two integer variables x and y to 10 and 20, respectively.
- It prints their values prior to swapping, uses their addresses to invoke the swap function, and then prints their values following the swap.
- The dereference operator * is used by the swap function to access the values pointed to by the two integer pointers it receives as arguments.
- The addresses of x and y are passed to the swap function using the & operator.
Q. What is the difference between a pointer to an object and a reference to an object in C++?
In C++, a reference acts as an alias for an existing variable or object—it is essentially another name for the same memory location and must be initialized when declared. Once set, a reference cannot be changed to refer to another object. On the other hand, a pointer is a variable that holds the memory address of another variable or object. Unlike references, pointers can be reassigned to point to different objects over their lifetime and can also hold a nullptr to indicate that they are not currently pointing to any object. Additionally, pointers support arithmetic operations, providing greater flexibility but also requiring careful handling to avoid errors. In summary, references offer safer, more constrained behavior, while pointers provide more control and versatility at the cost of additional complexity.
Q. Can a pointer point to another pointer in C++?
Yes, in C++, a pointer can point to another pointer. This is known as a pointer to a pointer or double pointer. A double pointer holds the address of another pointer, which in turn holds the address of a variable or object.
When working with class hierarchies in C++, what can hold the address of a pointer to the base class is another pointer to the base class or even a pointer to a pointer. This is useful when dealing with inheritance, polymorphism, and dynamically allocated objects, as it allows flexible handling of class pointers and facilitates dynamic binding in polymorphic scenarios.
Q. Can we return a pointer in C++?
Yes, we can return a pointer in C++. Here is an example of the same.
Code Example:
#include
using namespace std;
int* createArray(int size) {
int* arr = new int[size];
for (int i = 0; i < size; i++) {
arr[i] = i + 1;
}
return arr;
}
int main() {
int* ptr = createArray(5);
for (int i = 0; i < 5; i++) {
cout << ptr[i] << " ";
}
delete[] ptr;
return 0;
}
I2luY2x1ZGUgPGlvc3RyZWFtPgoKdXNpbmcgbmFtZXNwYWNlIHN0ZDsKCmludCogY3JlYXRlQXJyYXkoaW50IHNpemUpIHsKaW50KiBhcnIgPSBuZXcgaW50W3NpemVdOwoKZm9yIChpbnQgaSA9IDA7IGkgPCBzaXplOyBpKyspIHsKYXJyW2ldID0gaSArIDE7Cn0KCnJldHVybiBhcnI7Cn0KCmludCBtYWluKCkgewppbnQqIHB0ciA9IGNyZWF0ZUFycmF5KDUpOwoKZm9yIChpbnQgaSA9IDA7IGkgPCA1OyBpKyspIHsKY291dCA8PCBwdHJbaV0gPDwgIiAiOwp9CgpkZWxldGVbXSBwdHI7CgpyZXR1cm4gMDsKfQ==
Output:
1 2 3 4 5
Explanation:
In this code fragment, the createArray() function, which accepts an integer argument size and returns a pointer to an integer, is defined in this program.
- The process employs the new operator to assign memory space for an array of integers.
- It then proceeds to initialize the aforementioned collection with certain values and consequently returns a pointer to the array's first element.
- Next, we invoke createArray() with argument 5 in the main() function, and we store the resultant pointer in the ptr variable.
- Then, by employing pointer arithmetic, we traverse through the array and output each entry.
- Finally, we use the delete[] operator to release the memory that the new operator had allocated.
Q. What are the different types of pointers in C++?
Here are the wide range of pointers available in C++:
- Null Pointer: A pointer that is initialized to nullptr (or NULL in older code), indicating it doesn't point to any valid memory location.
- Void Pointer: A generic pointer that can point to any data type but must be cast to another pointer type before dereferencing.
- Pointer to Object: A pointer that points to an object of a specific class or structure.
- Pointer to Member: A pointer that points to a member of a class (either a data member or a member function).
-
Pointer to Structure: A pointer that points to an instance of a struct. It allows access to the members of the structure through the pointer using the arrow operator (->).
- Pointer to Function: A pointer that points to a function, allowing functions to be called indirectly.
- Pointer to Pointer: A pointer that holds the address of another pointer, enabling multiple levels of indirection.
- Smart Pointer: A pointer provided by the C++ Standard Library that manages the lifetime of an object automatically. Examples include std::unique_ptr, std::shared_ptr, and std::weak_ptr.
- Array Pointer: A pointer that points to the first element of an array. It allows for array traversal and manipulation.
- Dynamic Pointer: A pointer used with dynamic memory allocation (e.g., new and delete operators) to manage memory at runtime.
- Dangling Pointer: A pointer that continues to hold the address of a memory location that has been deallocated or freed.
Q. Can two pointers point to the same object?
Yes, in C++ languages, two pointers can point at the same object. In the event two pointers are employed to refer to identical objects, they shall indicate the same value as a result of utilizing one and the same memory location.
Q. How do you free memory for an object using a pointer in C++?
You can use the delete operator to free memory for an object in C++ using a pointer. The snippet below will give you an idea of how this is done.
// Dynamically allocating an object
MyClass* ptr = new MyClass();
// Freeing memory for the object
delete ptr;
In this instance, we engage in the dynamic allocation of an object belonging to the predefined class known as MyClass through the utilization of the new operator. The pointer to said object is subsequently deposited within a variable named ptr. To free the memory allocated for the object, we use the delete operator with the pointer.
Q. What is the difference between delete and delete[] in C++?
Memory allotted by new and new[] is released using delete and delete[] in C++, accordingly. The two approaches of memory deallocation for arrays are fundamentally different from one another. Also, memory allotted for a single item can be freed via delete. To release memory reserved for an array of objects, use delete[].
Test Your Skills: Quiz Time
This compiles our discussion on pointers to objects in C++, here are a few more interesting articles that you must check out:
- 51 C++ Interview Questions For Freshers & Experienced (With Answers)
- Strings In C++ | Functions, How To Convert & More (With Examples)
- Difference Between C And C++| Features | Application & More!
- 10 Best C++ IDEs That Developers Mention The Most!
- Typedef In C++ | Syntax, Application & How To Use It (With Examples)
An economics graduate with a passion for storytelling, I thrive on crafting content that blends creativity with technical insight. At Unstop, I create in-depth, SEO-driven content that simplifies complex tech topics and covers a wide array of subjects, all designed to inform, engage, and inspire our readers. My goal is to empower others to truly #BeUnstoppable through content that resonates. When I’m not writing, you’ll find me immersed in art, food, or lost in a good book—constantly drawing inspiration from the world around me.
Login to continue reading
And access exclusive content, personalized recommendations, and career-boosting opportunities.
Subscribe
to our newsletter
Comments
Add comment