'Copy Constructors of classes instantiating derived classes

I have unsuccessfully been trying to create a copy constructor of a class that instantiates a derived class.

Let's say I have the following pure virtual class:

class AbstractBar{
public:
    virtual void printMe() = 0;

};

Class Bar inherits from AbstractBar as follows:

class Bar: public AbstractBar {
    std::string name_;

public:
    explicit Bar(std::string name) : name_ {std::move(name)}{};

    void printMe() override { std::cout << name_ << std::endl; }
};

My class Foo now attempts to make use of polymorphism by declaring a pointer to type AbstractClass as follows:

class Foo{
    std::unique_ptr<AbstractBar> theBar_;

public:
    explicit Foo(std::unique_ptr<Bar> bar){
        theBar_ = std::move(bar);
    };

    void printBar(){
        theBar_->printMe();
    }
};

I do however want Foo to be copied so I add the following copy constructor:

    Foo(const Foo &other) {
        theBar_ = std::unique_ptr<AbstractBar>();
        *theBar_ = *(other.theBar_);
    }

And this is where it breaks.

What I gather is that this may be a problem since theBar in the copy constructor thinks it is pointing to an AbstractBar but when I try to copy the object it points to, in the next line, I actually give it a derived Bar class.

Is there a proper way to implement this copy constructor?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source