Click here to Skip to main content
15,892,746 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
As per information from internet there are two ways create a Final class:-
1. by using "final" keyword after class name(c++11)
C++
class end final
{ };

2. by creating a prefinal class with private constructor, making final class as friend of prefinal class and virtually inherit the prefinal class in final class.
C++
class preFinal
{
  preFinal(){}
  friend class FINAL;
};
class FINAL:virtual public preFinal  //No class can derive this class.
{
};
class Derived:public FINAL //Compilation error,private constructor of preFinal class
{};


But third option I can think of is, if we define constructor in private itself then also we can't inherit a class, as below:-

C++
class Final
{
   Final(){}
};
class Derived:public Final{  //This will give error as Final constructor is in private.
};
int main()
{
   Final fo;
}


What I have tried:

Then why we need final keyword or to create prefinal class(option-2)?

Can anyone please let me know any case in which we can inherit a class with private constructor?
Posted
Updated 11-Nov-18 17:30pm
v3

 
Share this answer
 
Thanks Richard,
You send me link for final keyword description. I wanted to know if I define the constructor in private to make a class as final is there any thing wrong in it.

BTW through your link I also came to know that we can use "final" keyword for preventing virtual function over-riding in derived class. So I am clear about final keyword usage now. But do we need to follow option 2 I mentioned above when we can achieve the same by just keeping constructor in private?
 
Share this answer
 
Comments
Richard MacCutchan 12-Nov-18 5:48am    
Do it the right way with the correct language specification. If you try to invent your own work around there is a chance that it will cause problems in the future.

Also, please do not post replies as solutions (which they are not), use the Reply button below the message you are referring to.
If you are making constructor as private to make it final, how you will make the object of that class?

class Final
{
private:
  Final(){}
public:
  // other members
};

void someFunc() {
   Final myFinal; // compilation error
}
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900