Aaron
Aaron

Reputation: 4480

Should copy constructor be private or public

I am writing an abstract class that will be a parent for several other classes. I am thinking the copy constructor should be made private because you are using an abstract class and there is nothing to copy. However, I am not a 100% sure.

Am I correct and if I am not why should it be public or protected?

Upvotes: 6

Views: 2936

Answers (3)

Mark Ransom
Mark Ransom

Reputation: 308130

By making the copy constructor private you'll help prevent inadvertent object slicing, where you make a copy of a derived class but lose all the properties of that derived class. The derived classes can make their own copy constructors that are public and do the right thing.

There's one case where the copy constructor should be protected instead of private, when the abstract class has data members. This doesn't happen very often. The base class can copy the base class members while the derived class copies its own members.

class AbstractBase
{
public:
    AbstractBase(const std::string &init) : wtf(init) {}
    virtual ~AbstractBase() {}
    void DoSomething() = 0;
protected:
    AbstractBase(const AbstractBase &r) : wtf(r.wtf) {}

    const std::string wtf;
};

class Derived : public AbstractBase
{
public:
    // ...
    Derived(const Derived &r) : AbstractBase(r), moredata(r.moredata) {}
private:
    int moredata;
};

Upvotes: 3

BЈовић
BЈовић

Reputation: 64223

The copy constructor should be private if you do not want objects of the class to be copied. Otherwise, it should be public.

Upvotes: 8

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726509

I think protected is the best choice: it leaves the decision on whether or not the object is copyable to the derived classes, while prohibiting the copying at the abstract class level, preventing the dreaded object slicing.

Upvotes: 8

Related Questions