Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Home » Tip Bank » C++
Language: C++
Expertise: Intermediate
Apr 6, 2002



Building the Right Environment to Support AI, Machine Learning and Deep Learning

Inhibit Derivation from a C++ Class

If no other classes can derive from a class, then you know that all the pointers to that class point to objects of a uniform size. This can simplify memory management and file storage. The idea is to first define a dummy class with a private default constructor. Then virtually derive all the other classes for which you want to inhibit derivation from the dummy class and declare them as friends of the dummy class:
class CDummy
  //Private default constructor
  CDummy() {}
  friend class CX1;
  friend class CX2;

The class CDummy is a virtual base for the classes CX1, CX2.
class CX1 : virtual public CDummy
  //Constructor, can invoke CDummy's private 
  CX1() {}

The constructor of CDummy is private, but CX1 is a friend, so it can invoke that private constructor. But here's what happens if you try to derive a class CY1 from CX1:
class CY1 : public CX1
  //Constructor, cannot invoke CDummy's private 
  CY1() {}

Because CY1 has CDummy as a virtual base, it must initialize it, but it cannot. You get a compile time error, for example in the case of the VC++ compiler you get the message:
"'CDummy::CDummy' : cannot access private member 
declared in class
George Anescu
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date