mardi 19 décembre 2017

Passing derived class to a function of base class argument

I have this code:

#include <iostream>

class Base {
  public:
  virtual void sayHello() {
    std::cout << "Hello world, I am Base" << std::endl;
  }
};

class Derived: public Base {
  public:
  void sayHello() {
    std::cout << "Hello world, I am Derived" << std::endl;
  }
};

void testPointer(Base *obj) {
  obj->sayHello();
}

void testReference(Base &obj) {
  obj.sayHello();
}

void testObject(Base obj) {
  obj.sayHello();
}

int main() {
  {
    std::cout << "Testing with pointer argument: ";
    Derived *derived = new Derived;
    testPointer(derived);
  }
  {
    std::cout << "Testing with reference argument: ";
    Derived derived;
    testObject(derived);
  }
  {
    std::cout << "Testing with object argument: ";
    Derived derived;
    testObject(derived);
  }
}

The output is:

Testing with pointer argument: Hello world, I am Derived
Testing with reference argument: Hello world, I am Base
Testing with object argument: Hello world, I am Base

My question is why only void testPointer(Base *obj), i.e. the pointer case, returns the result of derived instance of void sayHello(), is it because the dynamic memory allocation with new? What should I do to make the other two cases to return the result of the derived class function void sayHello()?

Aucun commentaire:

Enregistrer un commentaire