简体   繁体   中英

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?

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

我认为protected是最好的选择:它决定对象是否可以复制到派生类,同时禁止在抽象类级别进行复制,防止可怕的对象切片

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;
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM