Concept of Final Class in C++
•Class which Can't be inherited by other class, that class is called final class.
•Types of Final Class
1. Final class: Object of it will be on heap.
class final2 { public: static final2* Create() { return (new final2()) ; } private: ~final2() { ; } }; int main() { final2 *f ; f = final2::Create() ; // Object only on Heap }
No one can Inherit this final2 class. Suppose if one is going to inherit it then
class child : public final2 { public: child(){ ;} } ;
Now Error will come.Child class can't inherit final class.. Because destructor of final class is private.
2. Final class: Object of it will be on Stack
class temp { private: ~temp() {; } friend class Final; // Due to friend , Final class can use private member functions of temp class }; class Final: virtual public temp { // Define all data members and functions as you want public: Final() { ; } ~Final(); };
Now this final class can't be inherited by other class.Suppose one is going to inherit it to his class then,
Example:
Code: CPP
class Child : public Final { public: Child(){ ;} ~Child() { ;} };
Due to temp class is inherited virtually to Final class. So when
child class's constructor called, then first temp class constructor will
be called. By Child class's constructor, we are calling temp class
constructor. Child class can't call temp class's private destructor
because child is not a friend of temp class. This is the rule of C++.
Due to this rule in C++, Compiler sees that it is violating the rules, then it flashes error.
-Gaurav Singhal
No comments:
Post a Comment