Rothbard
asked on
Uncopyable class
In Item 6 of his book "Effective C++" (Third Edition), Scott Myers gives the following example of an "uncopyable" base class, which can be used to disable the copy constructor and assignment operator in derived classes:
1. Why is private inheritance used instead of public?
2. Why does it make any difference if Uncopyable's constructor and destructor are declared protected or private? After all, with private inheritance all base class methods become private in the derived class.
Thanks.
class Uncopyable
{
protected:
Uncopyable() {}
~Uncopyable() {}
private:
Uncopyable(const Uncopyable&);
Uncopyable& operator=(const Uncopyable&);
};
One then does the following:class Derived : private Uncopyable { ... };
I can see that this works, however I am puzzled by two things: 1. Why is private inheritance used instead of public?
2. Why does it make any difference if Uncopyable's constructor and destructor are declared protected or private? After all, with private inheritance all base class methods become private in the derived class.
Thanks.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Thanks to both!
Side notes:
Today C++ offer better functionalities to implements non-copyable behavior (also known as entity semantic): The delete keyword.
The error messages from the compiler will be clearer ("attempt to use a deleted function" instead of "function is private").
Sample code:
Open in new window