Saturday, January 5, 2008

Making a class Non Derivable in C++

CONCEPT USED:
Private members can be accessed only from within the class or by the friend of the class.

CODE SNIPPET:
class Usable;

class Usable_lock {
friend class Usable;
private:
Usable_lock() {}
Usable_lock(const Usable_lock&) {}
};

class Usable : public virtual Usable_lock {
public:
Usable();
Usable(char*);
// ...
};

Usable a;

class DD : public Usable { };

DD dd; // error: DD::DD() cannot access
// Usable_lock::Usable_lock(): private member

Complexity: INTERMEDIATE.

1 comment:

Anonymous said...

Hello. This is a good article on non-derivable technique. I was investigating this problem too. Unfortunately, the solution you have provided is not generic. What if you want to make one more non-derivable class but cannot modify original base class or don't want to spend time to write on more class for that purpose? Please look at the generic solution implemented as a Boost C++ libraries extension if you are interested -

http://www.jetsnail.com/tech-blog/38-cpp/52-noninheritable

I hope you will like it!