mardi 15 août 2017

C++ not calling derived class function when passing by const reference

The following is an abstract of my code:

Base class:

#include <iostream>
using namespace std;
class Base {
public:
    Base() { cout << "Base constructor" << endl; }
    ~Base() { cout << "Base destructor" << endl; }
    virtual void func(void) const { cout << "base" << endl; }
};

Derived class:

#include "Base.h"
class Derived : public Base {
public:
    Derived() { cout << "Derived constructor" << endl; }
    ~Derived() { cout << "Derived destructor" << endl; }
    void func(void) const { cout << "derived" << endl; }
};

Test class:

#include "Derived.h"

class Test {
public:
    const Base& base;
    Test(const Base& _base) : base(_base) { cout << "Test constructor" << endl; }
    void test() { base->func(); }
    ~Test() { cout << "Test destructor" << endl; }
};

main function for testing:

#include "Test.h"
int main(void) {
    Test* t = new Test(Derived());
    t->test();
    return 0;
}

When I run the main function, the Base version of func is being called.

However, if I change the main function to the following:

#include "Test.h"
int main(void) {
    Derived d;
    Test* t = new Test(d);
    t->test();
    return 0;
}

The Derived version of func is correctly called. I also tried to change const Base& base in Test to Base* base. And then construct Test using

Test* t = new Test(new Derivec())

It turns out that the Derived version of func is also correctly being called.

I was thinking that if I use either reference or pointer, the polymorphism is going to work.

Can anyone explain to me why the first version does not call the derived class method correctly?

Thanks a lot for helping!

Aucun commentaire:

Enregistrer un commentaire