In this inheritance program I create 2 classes which A is parent and B is child class . and i crate cons of both classes and also use Destructor, and both classes have tow objects . @ MY question is that when my program is run then its output show 2 Destructor of class a why ?
#include <iostream>
using namespace std;
class A
{
int a;
public:
A(int a1) // cons(A)
{
a = a1;
}
A() {} // Dis(A)
~A() { cout << "A Disturctor"<< endl; }
};
class B : public A // inheritance
{
int b;
public:
B(int b1) // cons (A)
{
b = b1;
}
~B() { cout << "B Disturctor" << endl; } // Dis(B)
};
int main()
{
A hamza(1);
B Ramza(4);
return 0;
}
Output:
B Disturctor
A Disturctor1
A Disturctor2
The first "A Disturctor" is for object "A hamza(1)". The second "A Disturctor" is for object "B Ramza(4)"
Since B inherits from A, when object of class B is destroyed, destructor of both class B and class A are called.