Friday, February 19, 2010

Inheritance .

In any inheritance Private members are not inherited .

Public Inheritance : things will come as it is , Protect base-->Protected deirved , Public base--> Public derived .

Private Inheritance : Things will come as Private Protected base-->Private deirved , Public base--> Private derived .

Protected Inheritance : Things will come as Protected Protected base -->Protected deirved , Public base--> Protected derived .

Virtual Inheritance : used in multiple and multilevel Inheritance to solve "THe famous Diamond problem "
Link : http://en.wikipedia.org/wiki/Virtual_inheritance

Monday, February 1, 2010

Private Constructor / Destructor In C++ and FINAL Class

Private Constructor : Means object cannot be created . but its useful in Singleton class where we provide on static function(or Friend function) to create Single object .

If Destructor is private class Cant be inherited

FINAL Class : Class which can't be inherited . In Java we have final calss facitlity.
Why is it required ? Lets say we have Class that doesn't have a virtual destructor; it may contain some dynamically allocated object. Now, if anyone inherits a class from it and creates the object of the derived class dynamically, it will Lead to Memory Leak . In this case we would like to finalise the class to avoid this leakage
How to do that ?
1) Making constructor Private . and providing static function for creation .
2) Private Destructor.
As static is there object will be created at heap and needs care while deletion .
How can we make object in stack.
3)better way : make a base class with Consturctor private and make derived class its firend so that it can access private Constructor .
Derive final class virtual public from this base class.
whenever anyone attempts to inherit a class from FinalClass and make an object of it, its constructor tries to call the constructor of Virtual base class. But the constructor of  base is private, so the compiler complains about this and it gives an error during the compilation because your Most derived class is not a friend of Base
Why Virtual derivation  helps here ?
Because of Virtual Inheritance rule :Since the most derived class's ctor needs to directly call the virtual base class's ctor 
If it would have been just public inheritance than derivation from final will be allowed ? because there Most derived constructor will call Final class ctor which will call base class ctor(private) . Here indirect relationship is enough.
In Virtual inheritance most derived class object will have two VPTR both pointing to same object of base class  

point : friendship is not inherited in the drive class
REF:
http://www.codeguru.com/cpp/cpp/cpp_mfc/stl/article.php/c4143

Followers