dcsimg
Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.


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

WEBINAR:

On-Demand

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:
  //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
{
public:
  //Constructor, can invoke CDummy's private 
constructor.
  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
{
public:
  //Constructor, cannot invoke CDummy's private 
constructor
  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
'CDummy'"
George Anescu
 
Comment and Contribute

 

 

 

 

 


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

 

 

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