I was messing around with inheritance in C++ and wanted to know if anyone had any insight on the way it functions. Code below
#include <iostream>
using namespace std;
class AA {
int aa;
public:
AA() {cout<<"AA born"<<endl;}
~AA(){cout<<"AA killed"<<endl;}
virtual void print(){ cout<<"I am AA"<<endl;}
};
class BB : public AA{
int bb;
public:
BB() {cout<<"BB born"<<endl;}
~BB() {cout<<"BB killed"<<endl;}
void print() {cout<<"I am BB"<<endl;}
};
class CC: public BB{
int cc;
public:
CC() {cout<<"CC born"<<endl;}
~CC(){cout<<"CC killed"<<endl;}
void print() {cout<<"I am CC"<<endl;}
};
int main()
{
AA a;
BB b;
CC c;
a.print();
b.print();
c.print();
return 0;
}
so I understand that when you inherit something you inherit constructors and destructors. So when I do , “BB b” it prints “AA born”. So the question I have
- Is an instance of AA created
- If yes, what is it called and how can I reference it?
- If no, why is the constructor being called
Inheritance implements the “IS-A” relationship. Every
BBis therefore also anAA.You can see this in a number of ways, the easiest to demonstrate is:
Here your
BBinstancebis being pointed at by a pointer which only thinks of itself as pointing to anAA. IfBBdidn’t inherit fromAAthen that wouldn’t be legal.The interesting thing is that when you call:
It still prints “I am BB”, despite the fact that the pointer you used is of type
AA *. This happens because theprint()method isvirtual(i.e. polymorphic) and you’re using a pointer. (The same would also happen with a reference too, but the type must be one of those for this behaviour to happen)