0

I wonder why static objects call parent method and dynamic objects child method in this example.

#include <string>
#include <iostream>
using namespace std;

class Father {
public:
    virtual string Info() {
        return "I am father";
    }
};

class Son : public Father {
public:
    string Info() {
        return "I am son";
    }
};

int main() {
    Father f = Son();
    cout << f.Info(); // I am father
    Father* pf = new Son();
    cout << pf->Info(); // I am son
    return 0;
}
Jan Turoň
  • 31,451
  • 23
  • 125
  • 169

3 Answers3

7

It is due to slicing - your f is actually an automatically located Father, the assigment Father f = Son() is actually Father f = Father(Son()), thus f's dynamic type is indeed Father, and as expected, Father::Info() will be invoked.

More info on slicing can be found in this post

Community
  • 1
  • 1
amit
  • 175,853
  • 27
  • 231
  • 333
1

This is polymorphism. When you allocate an object statically like this:

Son son();

You know at compile time that son is of type Son. If you allocate it dynamically you have a choice of storing Son objects in Son pointers or Father pointers. If you store them in Son pointers then it's the same as above. However if you store Son objects in Father type pointers:

Father* ptr = new Son()

then the compiler has no way of knowing which type of object Father pointer is pointing at. So at run time when it finds out it calls the appropriate version of Info.

atoMerz
  • 7,534
  • 16
  • 61
  • 101
1

Because, Father f = Son() create object of type Father and copy attributes from object Son (at this case no attributes to copy), so Father * pf = new Son() receives pointer to object Son, it actually may be any Father-derived object.

Finally, in your example you have 3 objects. Father f, unnamed object Son() which copy to Father f, and Father * pf that points to object of type Son.

atoMerz
  • 7,534
  • 16
  • 61
  • 101
Torsten
  • 21,726
  • 5
  • 24
  • 31