Archive | Polymorphism RSS for this section

Declare Your Default Constructor Private; Declare Your Class Non-Inheritable

There’s this book floating around: Effective C++. It contains tips on how not to be terrible at C++, and it’s not a terrible read too as far as programming books go. However, if you aren’t very careful, you can shoot yourself in the foot. Take item 6 for instance.

The gist of item 6 is: declare your default constructor, copy constructor, and operator= private if you don’t want them to be used. The compiler will declare these for you if you don’t declare them, so if you don’t want them to be used, you have to specifically disallow them. Having read this, I got into the habit of always making them private, and only allowing access to them as they become needed. This strategy worked fine until I tried to inherit from a base class with a private default constructor. Suddenly GCC decides to have a problem with this:

In file included from Seat.h:12:0, from Seat.cpp:8: Position.h:52:4: error: ‘clt::week3::Position::Position()’ is private Seat.cpp:22:28: error: within this context

With google proving unhelpful on this issue, I go through the process of creating a Visual Studio project and trying my code there. Visual Studio shows similar behavior. Has the lowly Chris Tetreault found a problem with the venerable Effective C++? As it turns out, no he didn’t. However, the book could have stood to elaborate on this subject. The book provides a base class that implements the uncopyable behavior, reproduced below:

class Uncopyable { protected: Uncopyable() {} // allow construction ~Uncopyable() {} // and destruction of // derived objects... private: Uncopyable(const Uncopyable&); // ...but prevent Uncopyable & operator=(const Uncopyable&); // copying };

The comments spell it out, that you have to make the default constructor protected, which is the same conclusion I came to in my troubleshooting. However, this is the only thing said on the subject. Either way, I guess I should have paid closer attention…

%d bloggers like this: