C++ Programming Language
Table of content:
- A Brief Intro To C++
- The Timeline Of C++
- Importance Of C++
- Versions Of C++ Language
- Comparison With Other Popular Programming Languages
- Conclusion
- Frequently Asked Questions
- Test Your Skills: Quiz Time
Table of content:
- 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
Table of content:
- 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
Table of content:
- Structure Of C++ Program: Components
- Compilation & Execution Of C++ Programs | Step-by-Step Explanation
- Structure Of C++ Program With Example
- Conclusion
- Frequently Asked Questions
- Test Your Skills: Quiz Time
Table of content:
- 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
Table of content:
- 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
Table of content:
- 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
Table of content:
- 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
Table of content:
- 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
Table of content:
- 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
Table of content:
- 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
Table of content:
- 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
Table of content:
- 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
Table of content:
- 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
Table of content:
- What is Memory Allocation in C++?
- The “new" Operator In C++
- The "delete" Operator In C++
- Dynamic Memory Allocation In C++ | Arrays
- Dynamic Memory Allocation In C++ | Objects
- Deallocation Of Dynamic Memory
- Dynamic Memory Allocation In C++ | Uses
- Conclusion
- Frequently Asked Questions
- Test Your Skills: Quiz Time
Table of content:
- What Is A Substring In C++ (Substr C++)?
- Example For Substr In C++
- Points To Remember For Substr In C++
- Important Applications Of substr() Function
- How to Get a Substring Before a Character?
- Print All Substrings Of A Given String
- Print Sum Of All Substrings Of A String Representing A Number
- Print Minimum Value Of All Substrings Of A String Representing A Number
- Print Maximum Value Of All Substrings Of A String Representing A Number
- Conclusion
- Frequently Asked Questions
- Test Your Skills: Quiz Time
Table of content:
- 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
Table of content:
- 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
Table of content:
- 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
Table of content:
- 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
Table of content:
- 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
Table of content:
- 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
Table of content:
- 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
Table of content:
- 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
Table of content:
- 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
Table of content:
- 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
Table of content:
- 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
Table of content:
- 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
Table of content:
- What Are 2D Vectors In C++?
- How To Declare 2D Vector In C++?
- How To Initialize 2D Vector In C++?
- C++ Program Examples For 2D Vectors
- How To Access & Modify 2D Vector Elements In C++?
- Methods To Traverse, Manipulate & Print 2D Vectors In C++
- Adding Elements To 2-D Vector Using push_back() Function
- Removing Elements From Vector In C++ Using pop_back() Function
- Creating 2D Vector In C++ With User Input For Size Of Column & Row
- Advantages of 2D Vectors Over Traditional Arrays
- Conclusion
- Frequently Asked Questions
- Test Your Skills: Quiz Time
Table of content:
- 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
Table of content:
- 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
Table of content:
- 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
Table of content:
- 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
Table of content:
- 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
Table of content:
- 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
Table of content:
- 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)
Table of content:
- What Is Friend Function In C++?
- Declaration Of Friend Function In C++ With Example
- Characteristics Of Friend Function In C++
- Global Friend Function In C++ (Global Function As Friend Function )
- Member Function Of Another Class As Friend Function In C++
- Function Overloading Using Friend Function In C++
- Advantages & Disadvantages Of Friend Function in C++
- 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
Table of content:
- 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
Table of content:
- 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
Table of content:
- 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
Table of content:
- 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
Table of content:
- What Is A Class And Object In C++?
- What Is An Object In C++?
- How To Create A Class & Object In C++? With Example
- 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++
- 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++
- Difference Between Structure & Class In C++
- Conclusion
- Frequently Asked Questions
Table of content:
- 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
Table of content:
- 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
Table of content:
- 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
Table of content:
- 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
Table of content:
- 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
Table of content:
- 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
Table of content:
- 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
Table of content:
- 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
Table of content:
- 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
Table of content:
- 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
Table of content:
- 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
Table of content:
- 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
Table of content:
- 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
Table of content:
- 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
Table of content:
- 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
Table of content:
- 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
Table of content:
- 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
Multiple Inheritance In C++ & Ambiguity Problems (+Code Examples)

The concept of inheritance is a fundamental feature of object-oriented programming languages. It allows us to create a new class (i.e., derived or child class) based on an existing class or classes (i.e., base or parent class). The derived class inherits properties (data members) and behaviors (member functions) from the base class, which is known as inheritance.
In this article, we will focus on multiple inheritance in C++ programming, its syntax, implementation, problems/ challenges, modes, and more with the help of detailed code examples.
What Is Multiple Inheritance In C++?
Multiple inheritance in C++ language allows a class to inherit members (data members and member functions) from multiple base classes. It's like a child learning different skills from different teachers.
- Multiple inheritance means that a derived class can have more than one parent class, and it inherits properties and behaviors from all of them.
- This is a powerful but complex concept of object-oriented programming that must be used with caution to avoid ambiguities.
How Does Multiple Inheritance In C++ Work?
We create a derived class/ child class that can inherit all public and protected members from multiple base classes. When an object of the derived class is initialized, the derived class constructor calls the base class constructors in the order they are listed in the declaration. And the destructor calls the base class destructors in the reverse order.
The logical diagram in the image above depicts what a multiple inheritance structure would look like. We have a single class named a child class, which inherits from n other classes denoted by Base Class 1, Base Class 2… and so on.
Syntax For Implementing Multiple Inheritance In C++
class Derived : access_specifier1 Base1, access_specifier2 Base2, ... {
// Derived class members and methods
};
Here,
- Derived: The name of the derived class that inherits from multiple base classes.
- access_specifier: It is a specifier that indicates if the base class members are accessible for the derived class. We can use public, protected, or private access specifiers.
- Base1, Base2, ...: The names of the base classes from which the derived class will inherit ( separated by commas).
Let’s see the implementation syntax of multiple inheritance for two-parent classes and one child class.
class Base1 {
public:
void func_Base1() {
// Base1 function implementation
}
};class Base2 {
public:
void func_Base2() {// Base2 function implementation
}
};class Derived : access_specifier1 Base1, access_specifier2 Base2 {
public:
void func_Derived() {// Derived class function implementation
}
};
Multiple inheritance can be used to model real-life scenarios where an entity possesses characteristics and behaviors from multiple sources.
Examples Of Multiple Inheritance In C++
We know the syntax and workings of multiple inheritance in C++. Let's look at practical examples to showcase how it actually works.
Example 1: Program Demonstrating Use Of Multiple Inheritance In C++
Imagine creating a class for a vehicle that inherits features from both a Car class and a GPS class. The Car class provides information about speed and fuel consumption, while the GPS class offers location and navigation capabilities. We can create a SmartCar class that combines the functionalities of a car and a GPS system using multiple inheritance.
Code Example:
#include <iostream>
// Base class for a Car
class Car {
public:
void drive() {
std::cout << "Car is driving." << std::endl;}
};
// Base class for a GPS system
class GPS {
public:
void navigate() {
std::cout << "GPS is navigating." << std::endl;}
};
// Derived class SmartCar inherits from both Car and GPS in public mode
class SmartCar : public Car, public GPS {
public:
void autoDrive() {
std::cout << "SmartCar is auto-driving." << std::endl;}
};
int main() {
SmartCar myCar; // Accessing inherited functions
myCar.drive(); // Calls Car's drive()
myCar.navigate(); // Calls GPS's navigate()
// Using the unique function of SmartCar
myCar.autoDrive(); // Calls SmartCar's autoDrive()
return 0;
}
Output:
Car is driving.
GPS is navigating.
SmartCar is auto-driving.
Explanation:
We begin the C++ program by including the <iostream> header file. Then-
- We create a base class called Car, which contains a public member function drive() that uses std::cout to print a phrase to the console.
- Then, we define a second base class called GPS, containing a public member function, navigate(), to print a phrase when called.
- Next, we define a derived class, SmartCar, using multiple inheritance. It publicly inherits from both the Car and GPS classes.
- This means that SmartCar inherits all the public member functions and attributes of both base classes.
- It also has a member function, autoDrive(), which prints a phrase using std::cout.
- Inside the main() function, we create an object of SmartCar class called myCar.
- We then use this object with dot operator to call the drive() function inherited from the Car class and call the navigate() function inherited from the GPS class.
- The functions print the string messages, 'Car is driving' and 'GPS is navigating', respectively.
- Lastly, we call the autoDrive() member function of the SmartCar class using the dot operator. It prints the phrase 'SmartCar is auto-driving' to the console.
- Finally, the main() function returns 0, indicating successful program execution.
Example 2: Using Multiple Inheritance In C++ To Perform Arithmetic Operations
In this example, we'll create a calculator class that inherits functionality from both an addition class and a subtraction class to perform arithmetic operations like addition and subtraction.
Code Example:
#include <iostream>
// Base class for addition operations
class Addition {
public:
int add(int a, int b) {
return a + b;}
};
// Base class for subtraction operations
class Subtraction {
public:
int subtract(int a, int b) {
return a - b;}
};
// Calculator class that inherits from both Addition and Subtraction
class Calculator : public Addition, public Subtraction {
public:
// Constructor
Calculator() {
std::cout << "Calculator is ready." << std::endl;}
// Function to perform both addition and subtraction
void performOperations(int num1, int num2) {
int resultAddition = add(num1, num2);
int resultSubtraction = subtract(num1, num2);
std::cout << "Addition result: " << resultAddition << std::endl;
std::cout << "Subtraction result: " << resultSubtraction << std::endl;}
};
int main() {
Calculator myCalculator;
int num1 = 10, num2 = 5;
myCalculator.performOperations(num1, num2);
return 0;
}
Output:
Calculator is ready.
Addition result: 15
Subtraction result: 5
Explanation:
- We create a base class, Addition, containing the public member function add(). It takes two integers, a and b, and returns their sum using the addition arithmetic operator.
- Then, we define a second base class, Subtraction with public member function subtract(), that takes two integers and returns their difference.
- Next, we create a derived class, Calculator, which publically inherits from both the Addition and Subtraction classes. Inside:
- We define a constructor, Calculator(), which prints the phrase 'Calculator is ready' when an object of class is created.
- Next, we define a member function, performOperations(), which performs both addition and subtraction using the inherited add() and subtract() methods.
- It takes two integer numbers as input and calculates their addition (stored in resultAddition) and subtraction (stored in resultSubtraction). The result is printed to the console using std::cout and std::endl, which moves the cursor to the next line.
- In the main() function, we create an instance of the Calculator class, object myCalculator.
- Next, we declare and initialize integer variables, num1 and num2, with values 10 and 5, respectively.
- Then, we call the performOperations() function on myCalculator object and pass num1 and num2 as parameters.
- The function uses the methods from derived classes to perform the operations and displays the results of addition and subtraction to the console.
Example 3: Getting Average Marks Of Two Subjects Using Multiple Inheritance In C++
Here, we will define two base classes, i.e., Maths and Science, representing marks obtained in math and science subjects, respectively. Then, we'll create a derived class Student that inherits from both Math and Science to calculate and display the average marks.
Code Example:
#include <iostream>
// Base class for math subject
class Maths {
public:
double mathMarks;
Maths(double math) : mathMarks(math) {}
void displayMathMarks() {
std::cout << "Math Marks: " << mathMarks << std::endl;}
};
// Base class for science subject
class Science {
public:
double scienceMarks;
Science(double science) : scienceMarks(science) {}
void displayScienceMarks() {
std::cout << "Science Marks: " << scienceMarks << std::endl;}
};
// Derived class Student inherits from both Maths and Science
class Student : public Maths, public Science {
public:
Student(double math, double science) : Maths(math), Science(science) {}
void calculateAverage() {
double average = (mathMarks + scienceMarks) / 2.0;
std::cout << "Average Marks: " << average << std::endl;}
};
int main() {
double mathMarks = 90.5;
double scienceMarks = 88.0;
Student student(mathMarks, scienceMarks);
student.displayMathMarks();
student.displayScienceMarks();
student.calculateAverage();
return 0;
}
Output:
Math Marks: 90.5
Science Marks: 88
Average Marks: 89.25
Explanation:
In this example C++ code,
- We first define base class, Maths containing:
- Public data member, mathMarks, of double data type to store the marks in the Maths subject.
- Next, we have a constructor, mathMarks(math), which initializes the mathMarks data member.
- Finally, we have a public member function displayMathMarks(), which prints the marks using std::cout.
- Then, we create a second base class, Science, containing:
- A public data member called scienceMarks of type double to store marks in the Science subject.
- A constructor, scienceMarks(science) to initialize the scienceMarks data member, and a displayScienceMarks() member function to print the marks.
- After that, we create a derived class, Student, which publically inherits from both the parent classes using multiple inheritance. Inside:
- We have a constructor Student(), which calls the constructors of the base classes to initialize the respective data members.
- Then, we define a member function, calculateAverage(), that calculates the average of the math and science marks and prints it to the console using std::cout.
- In the main() function, we first initialize two double type variables mathMarks and scienceMarks, with values 90.5 and 88.0, respectively.
- Next, we create an instance student of the Student class, passing the above variables to the constructor, which initializes the mathMarks and scienceMarks data members.
- We then use this object to call the displayMathMarks() and displayScienceMarks() functions to print the values to the console.
- Next, we call the calculateAverage() function on the student object using the dot operator to calculate the average and print it to the console.
Check out this amazing course to become the best version of the C++ programmer you can be.
Ambiguity Problem In Multiple Inheritance In C++
Ambiguity in multiple inheritance arises when a derived class inherits members (either data members or member functions) with the same name from multiple base classes. When this happens, the compiler cannot determine which version of the member to use in the derived class, resulting in an ambiguity error.
Let's illustrate this with a real-life example:
Suppose we have two base classes, Teacher and Musician, and a derived class, MusicTeacher, that inherits from both classes. Both Teacher and Musician have a member function called teach(). Since the derived class doesn't specify which teach() function to use, it leads to ambiguity.
Code Example:
#include <iostream>
class Teacher {
public:
void teach() {
std::cout << "Teaching general subjects." << std::endl;}
};
class Musician {
public:
void teach() {
std::cout << "Teaching music." << std::endl;}
};
class MusicTeacher : public Teacher, public Musician {
public:
// No specific teach() function defined in MusicTeacher
};
int main() {
MusicTeacher myTeacher;
// Ambiguity error when calling teach()
myTeacher.teach();
return 0;
}
Output:
Compilation error: request for member ‘teach’ is ambiguous
Explanation:
- We create a base class, Teacher, with a public teach() member function, which prints a message using std::cout when called.
- Next, we create another base class, Musician, containing a public teach() method that prints a different message when called.
- Then, we define a derived class MusicTeacher, which publicly inherits from both Teacher and Musician.
- This means that the public members of both base classes will be accessible in the derived class. This leads to ambiguity due to inherited member functions.
- Since MusicTeacher class does not have its own teach() function, it inherits two functions with the same name. One from the Teacher class, which teaches general subjects, and another from the Musician class, which teaches music.
- Now, inside the main() function, we create an instance myTeacher, of the MusicTeacher class.
- We then use this object to call teach() function. This leads to an ambiguity error, because the compiler cannot decide which teach() method to call— the one from the Teacher class or the one from the Musician class.
- Since there is no clear instruction on which method to use, the compiler throws an error.
Ambiguity Resolution In Multiple Inheritance In C++
To resolve this ambiguity due to multiple inheritance in C++ classes, we must explicitly specify which base class’s member function or data member we want to use in the derived class. There are two common ways to handle this:
- Using the scope resolution operator (::)
- Overriding the member function in the derived class.
Scope Resolution Operator (::) To Resolve Ambiguity Of Mulitple Inheritance In C++
In this method, we can explicitly specify the base class from which we want to access the member by using the scope resolution operator along with the base class's name.
Syntax:
base_class::member_name
Here,
- base_class: The name of the base class from which you want to access a member.
- member_name: The name of the member (function or data) that could lead to ambiguity.
Let’s solve the ambiguity in our music teacher example for multiple inheritance in C++ above by using the scope resolution operator.
Code Example:
#include <iostream>
class Teacher {
public:
void teach() {
std::cout << "Teaching general subjects." << std::endl;
}
};
class Musician {
public:
void teach() {
std::cout << "Teaching music." << std::endl;
}
};
class MusicTeacher : public Teacher, public Musician {
// No specific teach() function defined in MusicTeacher
};
int main() {
MusicTeacher myTeacher;
myTeacher.Teacher::teach(); // Calling teach() from Teacher
myTeacher.Musician::teach(); // Calling teach() from Musician
return 0;
}
Output:
Teaching general subjects.
Teaching music.
Explanation:
In continuation of previous example, we have the two base classes, Teacher and Musician with a teach() member function each. The derived class MusicTeacher publicly inherits from the two base classes.
- In the main() function, we create myTeacher object of MusicTeacher class.
- Then, we call the teach() function by specifying the name of the base class (Teacher), the scope resolution operator, and the function name teach(). This lets the compiler know to call teach() from the Teacher class.
- Similarly, we call teach() from Musician class by specifying the class name and using the scope resolution operator to specify which member function.
Override The Member Function To Resolve Ambiguity Of Mulitple Inheritance In C++
In C++, another way to resolve the ambiguity in multiple inheritance is by overriding the member function in the derived class. When you provide a custom implementation of a member function within the derived class, this overrides the inherited versions from the base classes. As a result, any potential ambiguity is eliminated from the get-go because the derived class's function always takes precedence.
In other words, the derived class’s version of the function will be called, and there will be no confusion between the functions inherited from the base classes.
How Does It Work?
- If the derived class defines its own version of a function (with the same name as in the base classes), it effectively replaces or overrides the inherited functions.
- The compiler will always call the derived class's function, ensuring no ambiguity occurs.
This approach is particularly useful when you want the derived class to have its own specific behavior, distinct from the base classes. Below is an example showcasing how you can give a custom definition of a member function to resolve the ambiguity problem of multiple inheritance in C++ classes.
Code Example:
#include <iostream>
class Teacher {
public:
void teach() {
std::cout << "Teaching general subjects." << std::endl;}
};
class Musician {
public:
void teach() {
std::cout << "Teaching music." << std::endl;}
};
class MusicTeacher : public Teacher, public Musician {
public:
void teach() {
// Custom implementation in MusicTeacher
std::cout << "Teaching both general subjects and music." << std::endl;}
};
int main() {
MusicTeacher myTeacher;
myTeacher.teach(); // Resolves ambiguity by using the overridden teach() in MusicTeacher
return 0;
}
Output:
Teaching both general subjects and music.
Explanation:
- In the code example, we define two base classes,Teacher and Musician, each with a member function named teach().
- Next, we define a derived class MusicTeacher that inherits from both Teacher and Musician using public inheritance. This class provides its own implementation of the teach() function.
- Inside the MusicTeacher class, we override the teach() function with a custom implementation.
- This implementation resolves the ambiguity by providing a unique behavior for the teach() function in the context of the MusicTeacher class. It combines the teaching of general subjects and music.
- In the main() function, we create an instance of the MusicTeacher class named myTeacher.
- We then use the instance with the dot operator to call the teach() function (i.e. myTeacher.teach()), which invokes the overridden teach() function in the MusicTeacher class, which prints ‘Teaching both general subjects and music.’
When overriding a member function in the derived class, the derived class's implementation takes precedence over the base class implementations, resolving the ambiguity.
Level up your coding skills with the 100-Day Coding Sprint at Unstop and claim the bragging rights, now!
The Diamond Problem In Multiple Inheritance In C++
The diamond problem occurs with multiple inheritance in C++ classes when a class inherits from two or more classes that share a common base class. The ambiguity arises because the derived class ends up with multiple instances of the common base class, leading to conflicts when accessing base class members.
Real-world example of the diamond problem with multiple inheritance in C++:
- Super Base Class: Say you have a base class, Human, representing a human being with various attributes.
- First Inheritance/ Base Class: We derive two classes, Person (representing individuals) and Employee (representing employees), both inherited from Human.
- Second Inheritance/ Derived Class: Then, we create a Manager class that inherits from both Person and Employee.
This creates two instances of Human class within Manager class: one from Person and one from Employee. When we try to access Human’s members from Manager, the compiler doesn't know which Human instance to refer to, causing ambiguity. This is called the diamond problem because of the structure of inheritance.
Note: The diamond problem differs from the general ambiguity problem with multiple inheritance. The diamond problem involves both multiple and multi-level inheritance, whereas ambiguity can arise in simple multiple inheritance in C++ classes.
Let's look at how this shows across code, after which we will proceed to see how to resolve the diamond problem when using multiple inheritance in C++.
Code Example:
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
return 0;
}
Output:
Human class constructor called
Person class constructor called
Human class constructor called
Employee class constructor called
Hello, I'm a person.
I am working as an employee.
Explanation:
Converting the real-life example above into code,
- We define a Human class with a private member variable name and a constructor that initializes the name and prints a message to the console.
- The class also contains a public member function introduce() that prints a message introducing the human by name.
- Then, we create two derived classes, Person and Employee, that inherit publicly from the Human class. Their respective constructors invoke the constructor of their base class to initialize the name data member.
- Each class also has a member function, i.e., greet() and work(), respectively. They print a message to the console using the std::cout statement.
- Then, we define a class Manager that inherits from Person and Employee classes. It contains a constructor which calls its base constructors to initialize the name data member.
- In the main() function, we create an instance manager of the Manager class and pass the value "Shivani" to the data member.
- This invokes the constructors for Employee and Person, which further invokes the Human class constructor twice.
- Then, we use the manager object with the dot operator to call the greet() and work() methods from the Person and Employee classes, respectively. Since the methods are unique, they do not lead to any confusion.
- After that, we have a commented line in the code that shows the diamond problem. Here, we have used the manager object to call the introduce() function from the Human base class.
- The Manager class can access introduce() through the Person and Employee classes since both share the base class.
- But without any further instructions, the compiler can't determine which instance of Human to use (inherited from Person or Employee), resulting in an ambiguity error.
- This problem arises because the Manager class inherits from the Person and Employee classes, which both inherit from Human. The structure of inheritance here lends the name– Diamond Problem.
The diamond problem occurs due to hybrid inheritance from both multilevel and multiple inheritance in C++. It can be solved using two main methods, i.e., virtual inheritance and explicit qualification with the scope resolution operator (::). Let's explore these methods in detail.
Method 1: The Scope Resolution Operator To Solve Diamond Problem
Just like in the case of ambiguity problem, the scope resolution operator allows us to explicitly specify which base class's member we want to access in the derived class. This resolves the ambiguity without changing the inheritance structure.
Syntax:
int main() {
derivedobj.Base1::memberName; // Access member from Base1
derivedobj.Base2::memberName; // Access member from Base2
Here,
- The derivedobj refers to the instance of the Derived class that inherits from the two base classes.
- Base1 and Base2 are the base classes that inherit from the Super Base class.
- memberName refers to the data member of the Super Base class that we want to access.
- The scope resolution operator (::) helps specify which base class to refer to when accessing the Super Base class member.
Let's look at an example showcasing the use of the scope resolution operator to solve the diamond problem of multiple inheritance in C++ classes.
Code Example:
#include <iostream>
class Human {
public:
Human(const std::string& name) : name(name) {}
void introduce() {
std::cout << "I am a human named " << name << std::endl;}
private:
std::string name;
};
class Person : public Human {
public:
Person(const std::string& name) : Human(name) {}
void greet() {
std::cout << "Hello, I'm a person." << std::endl;}
};
class Employee : public Human {
public:
Employee(const std::string& name) : Human(name) {}
void work() {
std::cout << "I am working as an employee." << std::endl;}
};
// The Manager class inherits from both Person and Employee
class Manager : public Person, public Employee {
public:
Manager(const std::string& name) : Person(name), Employee(name) {}
};
int main() {
Manager manager("Shivani");
manager.Person::introduce(); // Qualify using scope resolution operator
manager.greet(); // Calls greet() from Person
manager.work(); // Calls work() from Employee
return 0;
}
Output:
I am a human named Shivani
Hello, I'm a person.
I am working as an employee.
Explanation:
A version of the previous example, we have a super base class called Human, with a member function introduce(). Person and Employee classes inherit from Human, with their own functions, i.e., greet() and work(), respectively. We also have a Manager class that inherits from both Person and Employee, leading to the diamond problem.
- In the main() function, we create an object of the Manager class named manager and initialize the attribute name with the string value- "Shivani".
- Using this object, we call the introduce() function from the Person class. Here, we use the scope resolution operator and the name of the class from which we want to call introduce(), i.e., Person class.
- This lets the compiler know which route to take to call the introduce() method, avoiding any confusion. We can do the same using the Employee class.
- Then, we call the greet() and work() functions from the Person class and the Employee class, respectively. Here, we do not need the scope resolution operator since the compiler will automatically know which functions to invoke.
The example shows how to use the scope resolution operator to void the Diamond Problem by explicitly mentioning the base class we want to access.
Method 2: Virtual Inheritance To Solve Diamond Problem
Virtual inheritance is a feature in C++ that ensures that only one instance of a common base class is shared among multiple derived classes in a diamond-shaped inheritance hierarchy. It eliminates the possibility of repetitive instances.
In this method, we use the virtual keyword during inheritance. When the base class is marked as virtual, it signals the compiler to create a single instance of that base class within the hierarchy.
Let's discuss the solution to the diamond problem using virtual inheritance with the manager class example.
Code Example:
#include <iostream>
#include <string>
class Human {
public:
Human(const std::string& name) : name(name) {}
void introduce() {
std::cout << "I am a human named " << name << std::endl;
}
private:
std::string name;
};
class Person : virtual public Human {
public:
Person(const std::string& name) : Human(name) {}
void greet() {
std::cout << "Hello, I'm a person." << std::endl;
}
};
class Employee : virtual public Human {
public:
Employee(const std::string& name) : Human(name) {}
void work() {
std::cout << "I am working as an employee." << std::endl;
}
};
class Manager : public Person, public Employee {
public:
Manager(const std::string& name) : Human(name), Person(name), Employee(name) {}
};
int main() {
Manager manager("Shivani");
manager.introduce(); // Resolves ambiguity using virtual inheritance
manager.greet(); // Calls greet() from Person
manager.work(); // Calls work() from Employee
return 0;
}
Output:
I am a human named Shivani
Hello, I'm a person.
I am working as an employee.
Explanation:
Just like the previous two examples, we have a super base class Human with a constructor, data member name, and a member function introduce().
- We then define a Person and Employee class, which is derived virtually from Human using virtual inheritance/ keyword.
- By marking both Person and Employee as virtual public Human, we ensure that they share the Human base class, and Manager has only one Human instance.
- Then, we define a class Manager which inherits from both Person and Employee classes.
- It consists of a constructor, where, by definition, the Human class is explicitly initialized once, along with Person and Employee constructors. This helps avoid the duplication issue seen in regular multiple inheritance.
- In other words, in the Manager constructor, when we initialize Human(name), it ensures that the single Human instance is properly initialized.
- In the main() function, we create an instance of the Manager class named manager and initialize the name attribute with Shivani.
- Using this instance, we call the introduce() function (i.e., manager.introduce()). Unlike in the first example, when we call introduce() from Manager, there is no ambiguity, as only one Human instance exists.
- We also call the greet() and work() functions from the Person and Employee classes.
Also read: Diamond Problem In C++ & Its Resolutions Explained (+Examples)
Visibility Modes In Multiple Inheritance In C++
The visibility mode in multiple inheritance specifies how the members (variables and functions) of base classes are inherited by the derived class when multiple base classes are involved.
In other words, these modes determine the accessibility of base class members (data members and member functions) in the derived class, offering flexibility in designing class hierarchies to satisfy specific needs. It can be controlled using three distinct visibility modes–public, protected, and private.
Public Visibility Mode For Multiple Inheritance In C++
The public keyword stipulates that public members of the parent class remain public in the derived class, protected members remain protected, and the private members of the base class remain inaccessible in the derived class.
Syntax:
class Base1 {
//data member and member functions
};
class Base2 {
//data member and member functions
};class Derived : public Base1, public Base2 {
//data member and member functions
};
Here,
- Base1, Base2, and Derived are the names of the parent class 1, parent class 2, and the child class, respectively.
- The public keyword signifies that the derived class inherits publically from the parent classes, preserving the original accessibility modes.
Protected Inheritance Mode For Multiple Inheritance In C++
When using protected inheritance, the public and protected members of the base class become protected in the derived class. This means they are accessible within the derived class and any of its subclasses but not to other parts of the program. Private members of the base class remain inaccessible.
Syntax:
class Base1 {
//data member and member functions
};class Base2 {
//data member and member functions
};class Derived : protected Base1, protected Base2 {
//data member and member functions
};
Here,
- Base1, Base2, and Dervied, are the names of the base and derived classes, respectively.
-
The protected keyword used in the inheritance declaration specifies that the inherited members from Base1 and Base2 will be protected in Derived. This means that only the derived class and its subclasses can access the members of the base class.
Private Visibility Mode For Multiple Inheritance In C++
When using private keyword, both public and protected members of the base class become private members in the derived class. This means they are no longer accessible outside the derived class, even to subclasses of the derived class. As always, private members of the base class remain inaccessible for the derived class.
Syntax:
class Base1 {
//data member and member functions
};class Base2 {
//data member and member functions
};class Derived : private Base1, private Base2 {
//data member and member functions
};
Here,
- Base1, Base2 and Dervied are the base classes and derived class, respectively.
- The private access specifier used when deriving the Derived class indicates that the visibility mode is private. This means all base class members become private and can be accessed by the derived class only.
Let's look at an example showcasing the implementation of different visibility modes with multiple inheritance in C++ classes.
Code Example:
#include <iostream>
using namespace std;
// Base class for representing a person
class Person {
public:
Person(const std::string &name) : name(name) {}
void displayPersonInfo() {
std::cout << "Name: " << name << std::endl;
}
private:
std::string name;
};
// Base class for representing an address
class Address {
public:
Address(const std::string &area, const std::string &state)
: area(area), state(state) {}
void displayAddressInfo() {
std::cout << "Area: " << area << ", State: " << state << std::endl;
}
protected:
std::string area, state;
};
// Base class for Age (Protected Inheritance Example)
class Age {
protected:
int age;
public:
Age(int age) : age(age) {}
void displayAgeInfo() {
std::cout << "Age: " << age << std::endl;
}
};
// Derived class combining multiple inheritance with different visibility modes
class Contact : public Person, protected Address, private Age {
public:
Contact(const std::string &name, const std::string &area, const std::string &state, int age)
: Person(name), Address(area, state), Age(age) {}
void displayAddress() {
displayAddressInfo(); // Protected member from Address is accessible within this class
}
void displayAge() {
displayAgeInfo(); // Access private inheritance member via public function
}
};
int main() {
Contact myContact("Shivani", "S.Delhi", "Delhi", 34);
myContact.displayPersonInfo(); // Accessing public inheritance (Person) directly
// Accessing protected inheritance (Address) directly
// myContact.displayAddressInfo(); // Causes an error: displayAddressInfo is protected in Contact
// We can't access it outside the class directly.
// Accessing private inheritance (Age) directly
// myContact.displayAgeInfo(); // Causes an error: displayAge is private in Contact
// We can't access it outside the class directly.
myContact.displayAddress(); // Works because displayAddressInfo() is protected and is acceseiblefrom within Contact
myContact.displayAge(); // Works because displayAgeInfo() is called through a public method
return 0;
}
Output:
Name: Shivani
Area: S.Delhi, State: Delhi
Age: 34
Explanation:
In the C++ program example, we have three base classes and a derived class, which inherits from all three with different access specifiers.
- We first define class Person with a private data member name (string type), a public constructor and a public member function displayPersonInfo() which prints the name using std::cout.
- Then, we define a class Address with two protected data members area and state (both string type), a public constructor, and a public member function displayAddressInfo() that prints the data members.
- Next, we define a class Age with a protected data member age (int type), a public constructor and a public member function displayAgeInfo(), which prints the age.
- After that, we define a derived class Contact which inherits publically from Person class, protectedly from Address class, and privately from Age class. Inside, we have three public members:
- We have a constructor that invokes the constructor of all three base classes to intialise the data members when an object of Contact is created.
- Then, we define a member function displayAddress(), which includes a function call to the displayAddressInfo() method from Address class.
- Following this, we define the member function displayAge(), which calls the displayAgeInfo() method from Age class.
- In the main() function, we create an object contact, of the Contact class and initialize the members name, area, state and age with values Shivani, S.Delhi, Delhi, and 34.
- Next, we use the object with dot operator to call displayPersonInfo() function from Person. This goes off without an error because Contact inherits publicly from Person, making all its members accessible to the derived class directly.
- After that we have two sections of comments. In the first section, we use the same method to call the displayAddressInfo() method from Address. This will generate an error because Contact inherits protectly from Address, making it possible for only the derived class (and its subclasses) to access base members directly.
- Similarly, if we try to call displayAgeInfo() method directly using the object it will throw an error because Contact inherits privately from Age. This means only the derived class (and not its subclasses) can access base members.
- Next, we use the object to call the displayAddress() and displayAge() functions. These work without an error because we are accessing the protected and private (respectively) members from inside the derived class.
The example shows how visibility modes allow you to control the accessibility of base class members in the derived class. The choice of visibility mode in which we want to inherit the base class depends on the design and intended behavior of our derived classes.
Advantages & Disadvantages Of Multiple Inheritance In C++
Multiple inheritance opens the doors to a number of design possibilities. While it offers several advantages, it also brings its own set of complexities, which requires utmost consideration for error avoidance. In the section ahead, we'll discuss various advantages and disadvantages of multiple Inheritance in C++:
Advantages Of Multiple Inheritance In C++
- Code Reusability: Multiple inheritance encourages code reuse by enabling a class to inherit attributes and behaviors from several base classes. Instead of rewriting similar code, you can simply extend existing classes, making code more modular and maintainable.
- Rich Class Hierarchies: Multiple inheritance in C++ helps create rich, layered class hierarchies that model complex real-world scenarios more accurately.
- Flexibility: Multiple inheritance in C++ code provides flexibility in designing class hierarchies, allowing for more granular control over object modelling. You can combine features of different classes to create highly specialized classes tailored to specific needs.
Disadvantages Of Multiple Inheritance In C++
- Ambiguity: When a derived class inherits the same member from multiple base classes, the compiler can’t decide which one to use, leading to potential conflicts. Resolving this may require techniques like explicit qualification or virtual inheritance.
- Complexity and Readability: Multiple inheritance in C++ classes can make class hierarchies harder to manage and understand. Tracing the source of inherited members can become tricky, especially in large projects or deep inheritance chains.
- Diamond Problem: The Diamond Problem is a well-known issue in multiple inheritance in C++, where a class inherits from two or more classes that share a common base class. This can lead to redundancy and ambiguity.
Multiple Inheritance Vs. Multilevel Inheritance In C++
The table below highlights the key differences between multilevel and multiple inheritance in C++ classes.
Basis | Multilevel Inheritance | Multiple Inheritance |
Number of Base Classes | A derived class inherits from a single base class, and that derived class serves as a base for another. | A derived class can inherit from multiple base classes simultaneously. |
Class Hierarchy | Creates a hierarchical chain where each class inherits from the previous one. | Forms a flat structure where a class directly inherits from multiple base classes, often creating a more complex layout. |
Ambiguity | Minimal ambiguity as each class has a single base. | Higher potential for ambiguity, like the Diamond Problem, when multiple base classes share a common ancestor. Requires virtual inheritance to resolve. |
Complexity | Less complex with a straightforward linear hierarchy. | More complex due to possible conflicts and overlapping features from multiple base classes. |
Class Design | Best for scenarios with a clear hierarchy, where each level adds or modifies behavior. | Ideal for combining features from unrelated base classes. |
Example | Animal -> Bird -> Sparrow (clear chain of inheritance). | Manager inheriting from both Person and Employee, combining traits from both. |
Looking for guidance? Find the perfect mentor from select experienced coding & software experts here.
Conclusion
C++ offers three main types of inheritance: single, multilevel, and multiple inheritance, each with its pros and cons. Single inheritance provides a simple, straightforward hierarchy, while multiple inheritance allows a class to inherit from multiple sources, promoting code reuse.
However, multiple inheritance in C++ can introduce complexities and ambiguities, most notably the infamous Diamond structure problem, which demands resolution techniques like virtual inheritance or explicit qualification, the choice of which depends on the specific design goals of our program.
All in all, multiple inheritance offers flexibility but demands responsibility. With proper handling of ambiguities and inheritance conflicts, use of multiple inheritance in C++ code can significantly enhance the design and modularity of your code.
Also read- 51 C++ Interview Questions For Freshers & Experienced (With Answers)
Frequently Asked Questions
Q1. How do C++11 and later standards address issues related to multiple inheritance?
C++11 and later standards introduced several features to handle issues with multiple inheritance:
- override and final keywords: Help clarify which virtual functions can be overridden in the derived class (override–yes, final–no), reducing ambiguity.
- Smart pointers like std::shared_ptr and std::unique_ptr manage object lifetimes and ownership when dealing with multiple inheritance in C++ classes.
- Type traits and SFINAE (Substitution Failure Is Not An Error) allow sophisticated template programming when managing complex base classes with different characteristics.
Q2. What are the differences between public, private, and protected inheritance modes in multiple inheritance in C++?
When dealing with multiple inheritance in C++, the access specifiers determine how the members (attributes and functions) of the base class are inherited in the derived class. The differences between the three are listed in the table below:
Public Inhritance | Private Inheritance | Protected Inheritance |
---|---|---|
|
|
|
Q3. Are there any potential drawbacks or challenges associated with multilevel inheritance in C++?
Yes, multilevel inheritance can introduce several challenges:
- Complexity: As inheritance levels increase, the class hierarchy can become harder to understand and maintain.
- Inflexibility: Once established, refactoring or reorganizing a deep inheritance hierarchy can be challenging.
- Compile Time: Deeper hierarchies can increase compile time, particularly when working with online C++ compilers.
Q4. What is the difference between virtual inheritance and normal inheritance in the context of multiple inheritances?
In the context of multiple inheritance in C++, normal inheritance refers to the regular way of one derived class inheriting from multiple base classes. In contrast, virtual inheritance is a special mechanism that ensures there is only one shared instance of a common base class in a multiple inheritance hierarchy.
Aspect | Normal Inheritance | Virtual Inheritance |
---|---|---|
Object Creation | Each derived class creates its own separate instance of the base class. | Ensures only one shared instance of the common base class among all derived classes. |
Ambiguity Resolution | Ambiguities arise when the same-named member function is inherited from multiple base classes. | Resolves ambiguities like the Diamond Problem by ensuring a single shared base class instance. |
Memory Overhead | May lead to increased memory usage due to multiple copies of base classes. | Introduces minor overhead due to vtable management but is more memory-efficient. |
Q. How to call the parameterized constructor of the base class?
In multiple inheritance in C++, when a derived class inherits from multiple base classes, each of these base classes may have its own constructors. To call the parameterized constructor of a base class in C++, we need to explicitly invoke it in the initialization list of the derived class's constructor.
Let's consider an example where we have a derived class, Derived that inherits from two base classes, Base1 and Base2, both of which have parameterized constructors.
Code Example:
#include <iostream>
class Base1 {
public:
Base1(int value) {
std::cout << "Base1 parameterized constructor called with value: " << value << std::endl;}
};
class Base2 {
public:
Base2(int value) {
std::cout << "Base2 parameterized constructor called with value: " << value << std::endl;}
};
class Derived : public Base1, public Base2 {
public:
Derived(int value1, int value2) : Base1(value1), Base2(value2) {
std::cout << "Derived constructor called." << std::endl;}
};
int main() {
Derived derivedObject(10, 20);
return 0;
}
Output:
Base1 parameterized constructor called with value: 10
Base2 parameterized constructor called with value: 20
Derived constructor called.
Explanation:
In the above code snippet-
- When defining its constructor in the Derived class, we use a colon (:) to introduce the initialization list. Within this initialization list, we explicitly call the constructors of the base classes.
- In the Derived constructor, we specify Base1(value1) and Base2(value2). This means that we're calling the parameterized constructors of Base1 and Base2 with the provided values value1 and value2.
- When we create an object of the Derived class in the main() function, i.e., Derived derivedObject(10, 20), the constructors of Base1 and Base2 are called first with the respective values, followed by the Derived class's constructor.
Q. Are there alternative approaches to multiple inheritance in C++ for achieving code reusability and flexibility?
Some alternatives to multiple inheritance in C++ classes include:
- Composition: Reuse functionality by including objects of other classes as members, promoting encapsulation and flexibility.
- Mixin Classes: It is a form of multiple inheritance where base classes define interfaces or traits to mix specific behaviors into a derived class.
- Abstract Base Classes: Define interfaces using pure virtual functions (abstract classes), allowing derived classes to implement specific behaviors as per their own requirement.
Q. What is the exact order of destructors in the case of virtual/ multiple inheritance in C++?
When dealing with multiple inheritance in C++, it's crucial to understand the exact order in which destructors are called, especially in scenarios involving virtual inheritance. The order of destructor execution is important to ensure proper cleanup of resources in complex class hierarchies. Let's break down the rules for destructor order in multiple and/or virtual keyword situations.
Example: Suppose you have a class hierarchy with a most derived class D, meaning the object originally created was of class D. Additionally, D inherits multiply (non-virtually) from two base classes, B1 and B2. Each of these base classes may further inherit from other classes, creating a more complex inheritance hierarchy.
The order in which destructors are called is as follows:
- The destructor for the most derived class, D, runs first.
- The destructors for the non-virtual base classes are called in reverse declaration order. This means that the base class declared last (closest to the derived class) will have its destructor called first, followed by the destructor of the base class declared earlier. In the scenario with classes D, B1, and B2, the destructor order will be D, B2, and B1.
- This rule is applied recursively for nested inheritance. For example, if B1 inherits from B1a and B1b, and B2 inherits from B2a and B2b, the destructor order becomes D, B2, B2b, B2a, B1, B1b, B1a.
- After the above steps, virtual base classes are handled. The destructors for virtual base classes are executed in a specific order.
- The order follows a depth-first left-to-right traversal of the graph of base classes, where left to right refers to the order of appearance of base class names.
- Virtual base classes are unique, i.e., they are not destructed multiple times if they appear in the hierarchy multiple times.
- The destructor order for virtual base classes is determined based on the left-to-right order of appearance of their names in the inheritance hierarchy.
Quiz Time!!!
This compiles our discussion on multiple inheritance in C++. Here are a few more interesting topics that you should know about:
- C++ Type Conversion & Type Casting Demystified (With Examples)
- Function Prototype In C++ | Definition, Purpose & More (+Examples)
- Friend Function In C++ Classes | Types, Uses & More (+Examples)
- Hierarchical Inheritance In C++ Explained With Real-Life Examples
- C++ Exception Handling | Use Try, Catch, & Throw (+Examples)
- Data Abstraction In C++ | Types, Use-Cases & More (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.
Comments
Add commentLogin to continue reading
And access exclusive content, personalized recommendations, and career-boosting opportunities.

Subscribe
to our newsletter
Sanchit Dhale 1 month ago