0

It is not very clear for me how and why can I give the function WhatType() arguments of type Derived1 and Derived2, and why the output is:

ob is referencing an object of type 4Base
ob is referencing an object of type 8Derived1
ob is referencing an object of type 8Derived2
#include <iostream>
#include <typeinfo>
using namespace std;


class Base {public: virtual void f () { } };
class Derived1: public Base { };
class Derived2: public Base { };

void WhatType(Base &ob){
cout << "ob is referencing an object of type " << typeid(ob).name() << endl;}

int main() {
    Base b;
    Derived1 d1;
    Derived2 d2;
    WhatType(b);
    WhatType(d1);
    WhatType(d2);

    return 0;
}


I think I have seen before this type of "problem" and kind of memorized how it happens, but I would like to have some rigorous explanation.

Johnny
  • 447
  • 2
  • 8
  • 2
    Remember that inheritance is an *is a* relationship. `Derived1` *is a* `Base`. – Some programmer dude May 23 '21 at 09:02
  • 2
    This is the whole purpose of polymorphism, so that's by design. You should find an explanation for in any good [C++ book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). Explaining how polymorphism works is probably beyond the scope of SO. – Aconcagua May 23 '21 at 09:05

0 Answers0