Answer to Question #106523 in C++ for Udit kumar

Question #106523
How to stop class inheritance in c++ with condition that object
creation should be allowed.
1
Expert's answer
2020-03-26T09:59:38-0400

// Stopping of class inheritance with condition that object creation should be allowed

// in C++ can be done by means of private constructor with virtual inheritance and friend class


#include<iostream>


using namespace std; 


class Final;


class Helper

    Helper() // private constructor

    {

      cout << "Constructor of Helper class to simulate Final class. ";

    };

  friend class Final; // friend class

}; 

  

class Final : virtual Helper // virtual inheritance

  public: 

    Final() // this constructor can call the private constructor of Helper class because Final and Helper are friends

    {

      cout << "Constructor of Final class which cannot be inherited but instantiated. ";

    };

}; 


// the code below shows inheritance attempt and throws an error if uncommented

// class Child : public Final

// { 

//  public: 

//    Child() // this constructor tries to call the private constructor of Helper and cannot

//    {

//      cout << "Constructor of Child class which is tried to be inherited. ";

//    };

// }; 

  

int main() 

  Final f; // can be instantiated

  //Child c; // cannot be inherited

  return 0;


Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS