Search code examples
c++copyvirtualc++03

Can a copy constructor be defined in the base class and still handle derived class circumstances?


I have a class structure like below:

class P {
    public:
        virtual std::auto_ptr<P> clone() const=0;
};

class A : public P {
    public:
        std::auto_ptr<P> clone() const {
            return std::auto_ptr<P>(new A(*this));
        }
};

class B : public P {
    public:
        std::auto_ptr<P> clone() const {
            return std::auto_ptr<P>(new B(*this));
        }
};

class C : public P {
    public:
        std::auto_ptr<P> clone() const {
            return std::auto_ptr<P>(new C(*this));
        }
};

This is just the code for the copy constructors: classes A, B, C all have different code otherwise. There's a lot of code reduplication here, can it be simplified?


Solution

  • Can a copy constructor be defined in the base class and still handle derived class circumstances?

    In general, the short answer is "No".

    It works fine if the compiler generated copy constructors are sufficient.

    If a derived class is defined such that the compiler generated copy constructor is not adequate, there is no way to get around the need to define one in the derived class.