Question

I have a class (class A) which inherits another class (class B).

class A: public B

Class B disabled copy construct and assignment operator (due to not allow a copy).

private:
 B(const B&);
 B& operator=(const B&);

My question is that should I also disable copy construct and assignment operator in the derived class as well or is it okay if I did not define both.

Was it helpful?

Solution 2

The question is rather, should you re-enable it. If any base or member is noncopyable, your class will be noncopyable by default. Generally, you won't want to remove it, because it will be difficult or impossible to give it reasonable semantics. But there are notable exceptions: if the base class is abstract, for example, you may want to enable the copy constructor (but not assignment) in the derived class in order to support cloning.

OTHER TIPS

Subclasses should have the same or stricter [preconditions, post conditions and invariants] than their parent classes. This is the Liskov Substitution Principle. So, you should not re-enable copy construction etc/whatever in the derived class, since you will be loosening the contract of the base class.

If you find you need to do it (or would really like to do it), then it may be a sign that you need to rethink your design.

Disallowing copy-constructor and assignment operator of base class will cause that the copy-constructor and assignment operator of derived class won't be usable as well:

class B {
public:
    B() { }
private:
    B(const B&);
    B& operator=(const B&);
};

class A : public B { };

In this case you don't need to explicitly disallow these for derived class, since the default implementation will have to use the parent's implementation first. So if you don't try to access these in your code:

int main() {
    A a;
}

it will be perfectly valid. However if you try to copy:

int main() {
    A a;
    A a2 = A(a);
}

compiler will complain about class A trying to access private members of B (however semantically the second scenario shouldn't happen).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top