In java a final class is a class that cannot be derived. How
can you make a similar class in C++

Answer Posted / cpp master

Using virtual base classes. The most derived class has to
initialize all the virtual base class in the inheritance
hierarchy. To make such a class simply create a empty class
with a private constructor and mark the class to be made
non derivable as the friend of that class. Now simply
public virtually derive the non derivable with the empty
class. Below is the example code:

class UnDerivable;

class dummy{
private:
dummy(){}
friend class UnDerivable;

};


class UnDerivable: virtual public dummy
{
};

//try deriving fro the underivable class
class deriveUnderivable:public UnDerivable
{
};


int main()
{
UnDerivable ud;
deriveUnderivable uud; //will give an error
return 0;
}

Is This Answer Correct ?    1 Yes 0 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

what is C++ objects?

894


Explain the uses of static class data?

838


What are the differences between the function prototype and the function defi-nition?

823


Define namespace in c++?

830


Is main a class in c++?

750


What is the average salary of a c++ programmer?

768


What is array give example?

781


Is overriding possible in c++?

763


What can c++ be used for?

804


Explain terminate() and unexpected() function?

818


Is it legal in c++ to overload operator++ so that it decrements a value in your class?

816


What is iterator in c++?

844


How did c++ get its name?

766


Why is c++ so fast?

733


Define 'std'.

891