Search

Wednesday, July 14, 2004

C++ - Stop people deriving from your class

One of my friends was facing a problem while trying to write a class B so that no one would be able to inherit from it. He used code as below.



class B; // forward declaration

class Prot // this class is used to stop the inheritance
{
public:
friend class B; // allow only B access to ctors
private:
Prot(){}; // make all ctors private
Prot(const Prot &p){};
};

// class that cannot be inherited from
class B: public Prot // inherit from prot. Since B is friend of Prot it'll work
{
public:
B();
int a;
};

class D : public B
{
public:
int d;
};

D d; // this should fail




However D was still able to inherit from B. What he missed was using virtual inheritance for inheriting from Prot as follows


class B: public virtual Prot // inherit from prot
{
// ...
}

this lead to the bug. Without virtual inheritance the call does not go via the vtable and D is able to access Prot's ctor as it is merged with that of B.

No comments: