nstructor Calling, Multiple Inheritance, Diamond Problem, Method Overloading,
1. Constructor Calling in C++:
When you create an object of a class, its constructor gets called automatically. Example:
#include <iostream>
using namespace std;
class Base {
public:
Base() {
cout << "Base class constructor called" << endl;
};
class Derived : public Base {
public:
Derived() {
cout << "Derived class constructor called" << endl;
};
int main() {
Derived obj; // Both Base and Derived constructors will be called
return 0;
}
2. Multiple Inheritance in C++:
Multiple inheritance allows a derived class to inherit from more than one base class.
#include <iostream>
using namespace std;
class A {
public:
void showA() {
cout << "Class A" << endl;
};
class B {
public:
void showB() {
cout << "Class B" << endl;
};
class C : public A, public B {
public:
void showC() {
cout << "Class C" << endl;
}
};
int main() {
C obj;
[Link]();
[Link]();
[Link]();
return 0;
3. Diamond Problem in C++:
The diamond problem occurs when a class inherits from two classes that both inherit from a single
class.
#include <iostream>
using namespace std;
class A {
public:
A() {
cout << "Constructor of A called" << endl;
void show() {
cout << "Class A" << endl;
};
class B : virtual public A {
public:
B() {
cout << "Constructor of B called" << endl;
};
class C : virtual public A {
public:
C() {
cout << "Constructor of C called" << endl;
};
class D : public B, public C {
public:
D() {
cout << "Constructor of D called" << endl;
};
int main() {
D obj;
[Link](); // No ambiguity due to virtual inheritance
return 0;
}
4. Method Overloading in C++:
Method overloading is when two or more methods in the same class have the same name but
different parameters.
#include <iostream>
using namespace std;
class MathOperations {
public:
int add(int a, int b) {
return a + b;
double add(double a, double b) {
return a + b;
};
int main() {
MathOperations obj;
cout << "Sum (int): " << [Link](5, 3) << endl;
cout << "Sum (double): " << [Link](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
already defined in its base class.
#include <iostream>
using namespace std;
class Base {
public:
virtual void show() {
cout << "Base class show method" << endl;
};
class Derived : public Base {
public:
void show() override {
cout << "Derived class show method" << endl;
};
int main() {
Base* basePtr;
Derived obj;
basePtr = &obj;
basePtr->show(); // Calls Derived class show() method because of overriding
return 0;