In C ++ there are three types of inheritance:
Any of these three types of inheritance can be modified withvirtualKeyword. in my experience interviewing candidates for C ++ positions, I 've learned that the average programmer does not know how these are used, or even what they mean. so I thought I wocould go over them here.
The three access Modifierspublic,protectedAndprivateAre analogous to the access modifieres used for class members.
-
Public
-
When a base class is specified
publicIE:
class c : public base {};The base class can be seen by anyone who has access to the derived class. That is, any members inherited from
baseCan be seen by code accessing
c.
-
Protected
-
When a base class is specified
protectedIE:
class c : protected base {};The base class can only be seen by subclasses
C.
-
Private
-
When a base class is specified
privateIE:
class c : private base {};The base class can only be seen by the class
CItself.
Examples of how this plays out:
struct X {
public:
void A() {}
};
Struct y {
Public:
Void B (){}
};
Struct Z {
Public:
Void C (){}
};
Struct Q: Public X, protected y, private Z {
Public:
Void test ()
{
A (); // OK
B (); // OK
C (); // OK
}
};
Struct R: Public q {
Public:
Void Test2 ()
{
A (); // OK
B (); // OK
C (); // not OK
Q t;
Y * Y = & T // OK
Z * z = & T // not OK
}
};
Int main (INT argc, char ** argv ){
Q T1;
T1.a (); // OK
T1. B (); // not OK
T1.c (); // not OK
R t2;
T2.a (); // OK
T2. B (); // not OK
T2.c (); // not OK
X * x = & T1; // OK
Y * Y = & T1; // not OK
Z * z = & T1; // not OK
X = & T2; // OK
Y = & T2; // not OK
Z = & T2; // not OK
}
What about virtual?
Oh right. Virtual is only useful when multiple inheritance is involved and the same class appears in the inheritance graph more than once. If the inheritance is declaredvirtualAll instances of the class are merged into one sub object and that sub object is initialized once. If the class that appears multiple times in the inheritance graph is not declaredvirtualOne sub object is created for each instance of the class and the class is initialized multiple times.
Be careful! If the class is inherited sometimes as virtual and sometimes not, the virtual instances are merged and the non-virtual instances are not, giving you a mix of behavior.