Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Polymorphism in C++ does not work correctly with reference

I have a simple code which doesn't work correctly with reference (polymorphism).

#include <iostream>
#include <string>

class Base {
public:
    Base() {}
    virtual ~Base() {}
    virtual std::string text() const {
        return "Base";
    }
};

class Derived: public Base {
public:
    Derived(Base& _b): b(_b) {}
    virtual ~Derived() {}
    virtual std::string text() const {
        return b.text() + " - Derived";
    }

private:
    Base& b;
};

int main(int argc, char const *argv[])
{
    Base b;
    Derived d1(b);
    std::cout << d1.text() << std::endl;

    Derived d2(d1);
    std::cout << d2.text() << std::endl;
    return 0;
}

And output:

Base - Derived
Base - Derived

The second line in output I expected: Base - Derived - Derived. I read some resources and polymorphism work perfectly with reference and pointer but in this situation, it doesn't. If I replace reference by pointer, it work again. So, anybody can give me some explainations?

Thanks so much!

like image 662
Jack Cood Avatar asked Dec 04 '25 10:12

Jack Cood


1 Answers

You're invoking the default copy constructor to Derived. Therefore when finished d2 will be a simple member-copy of d1, and both their b members will reference the same Base instance.

To prove this, add this to your Derived class

class Derived: public Base {
public:
    Derived(Derived& d) : b(d) {}
    Derived(Base& _b): b(_b) {}
    virtual ~Derived() {}
    virtual std::string text() const {
        return b.text() + " - Derived";
    }

private:
    Base& b;
};

With this your output will become:

Base - Derived
Base - Derived - Derived

And just note, this is not a grand idea or a stellar learning example of polymorphism. (But it is an interesting example of construction overriding). Also note this is NOT a typical override of default copy-construction (where the parameter is a const-ref-type). Thus part of the reason this is not the greatest sample.

like image 50
WhozCraig Avatar answered Dec 07 '25 01:12

WhozCraig



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!