noob noob - 1 month ago 4x
C++ Question

Inheritance in C++

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;
AA() {cout<<"AA born"<<endl;}
~AA(){cout<<"AA killed"<<endl;}
virtual void print(){ cout<<"I am AA"<<endl;}

class BB : public AA{
int bb;
BB() {cout<<"BB born"<<endl;}
~BB() {cout<<"BB killed"<<endl;}
void print() {cout<<"I am BB"<<endl;}

class CC: public BB{
int cc;
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;
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

  1. Is an instance of AA created

  2. If yes, what is it called and how can I reference it?

  3. If no, why is the constructor being called


Inheritance implements the "IS-A" relationship. Every BB is therefore also an AA.

You can see this in a number of ways, the easiest to demonstrate is:

BB b;
AA *aptr = &b;

Here your BB instance b is being pointed at by a pointer which only thinks of itself as pointing to an AA. If BB didn't inherit from AA then 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 the print() method is virtual (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)