Link to home
Start Free TrialLog in
Avatar of Rothbard
RothbardFlag for United Kingdom of Great Britain and Northern Ireland

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:

class Uncopyable
{
protected:
	Uncopyable() {}
	~Uncopyable() {}

private:
	Uncopyable(const Uncopyable&);
	Uncopyable& operator=(const Uncopyable&);
};

Open in new window

One then does the following:

class Derived : private Uncopyable { ... };

Open in new window

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
Avatar of Zoppo
Zoppo
Flag of Germany image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Hi,

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:
class Uncopyable
{
public:
	Uncopyable(Uncopyable const&) = delete;
	Uncopyable& operator=(Uncopyable const&) = delete;
};

class Derived : private Uncopyable { ... };

Open in new window

Avatar of Rothbard

ASKER

Thanks to both!