Wednesday, April 13, 2005

Inheritance! Inheritance! Inheritance!

One of the key concepts in object oriented programming paradigm is Inheritance. Today Im going to show you an interesting thing for most of the C++, OO and .Net guys.
In OO and C++ there are three levels of inheritance is available for the class members as public, protected and private.
And the accessibility of your base classs members depends on two factors.

The way the derived class declares its class head (public, protected or private)
Access speceifier given for the class member (public, protected or private)
If you mark members as private in your base class, those members are inaccessible regardless of the derivation access.
If you mark members as protected in your base class, and if you do private derivation those members become private in the derived class.
If you mark members as protected in your base class, and if you do protected derivation those members become protected in the derived class.
If you mark members as protected in your base class, and if you do public derivation those members become protected in the derived class.
If you mark members as public in your base class, and if you do private derivation those members become private in the derived class.
If you mark members as public in your base class, and if you do protected derivation those members become protected in the derived class.
If you mark members as public in your base class, and if you do public derivation those members become public in the derived class.


Well those rules are for the old C++ folks. Take a careful look at the 2 scenarios highlighted.
In .Net the way those two works is radically different. .Net supports public inheritance only.
But when a class is inherited with public access the base classs protected members will become private to the derived class.

Consider the following 3 classes in C++
#include
class A
{
protected: void fa()
{printf("fa called"); }
};
class B : public A
{
public: void fb(){fa();}
};
class C : public B
{
public: void fc(){fa();}
};
int main()
{
C c;
c.fc();
return 0;
}
In C++ it will just work fine according to the rules I just described above. But if you make them managed classes you will not be able to call fa() from class c.

0 Comments:

Post a Comment

<< Home