CPP Inheritance Concepts
CPP Inheritance Concepts
When you create an object of a class, its constructor gets called automatically. Example:
#include <iostream>
class Base {
public:
Base() {
};
public:
Derived() {
};
int main() {
return 0;
}
2. Multiple Inheritance in C++:
Multiple inheritance allows a derived class to inherit from more than one base class.
#include <iostream>
class A {
public:
void showA() {
};
class B {
public:
void showB() {
};
public:
void showC() {
}
};
int main() {
C obj;
obj.showA();
obj.showB();
obj.showC();
return 0;
The diamond problem occurs when a class inherits from two classes that both inherit from a single
class.
#include <iostream>
class A {
public:
A() {
void show() {
};
class B : virtual public A {
public:
B() {
};
public:
C() {
};
public:
D() {
};
int main() {
D obj;
return 0;
}
Method overloading is when two or more methods in the same class have the same name but
different parameters.
#include <iostream>
class MathOperations {
public:
return a + b;
return a + b;
};
int main() {
MathOperations obj;
cout << "Sum (double): " << obj.add(5.5, 3.3) << endl;
return 0;
}
5. Method Overriding in C++:
Method overriding occurs when a derived class provides its own implementation of a method
#include <iostream>
class Base {
public:
};
public:
};
int main() {
Base* basePtr;
Derived obj;
basePtr = &obj;
basePtr->show(); // Calls Derived class show() method because of overriding
return 0;