|
|||||
| | |||||
|
C++ provides three kinds of inheritance: public, protected and private (the default). Public inheritance corresponds to the 'IsA' relationship, private and protected inheritance have different and less readily formulable meanings.
when do we use which kind of inheritance?
| | ||
| Use private derivation when a derived object is not considered a kind of base object and the base class simply supplies code to make the derived class easier to write | ||
| Base Class | Derived Class | |
| Private Members | become | hidden and not accessible except through member functions of base class |
| Protected Members | become | Private Members |
| Public Members | become | Private Members |
| Base Class | Derived Class | |
| Private Members | become not accessible | |
| Protected Members | become | Protected Members |
| Public Members | become | Protected Members |
| Use public derivation when a derived object is a kind of base object. When the declaration of a derived class contains the keyword public preceding the base class name, objects of the derived class can be treated as if they were instances of the base class. In particular, an object of the derived class can be used to invoke member functions or access data members defined for the base class; | ||
| Base Class | Derived Class | |
| Private Members | become | not accessible: can be accessed by non-static member functions and friend functions through public or protected member functions of the base class |
| Protected Members | become | Protected Members ... protected data members of base class are accessible in derived class without using the access methods |
| Public Members | become | Public Members ... and accessible to members outside of the class |
When above we say that private members of the base class are not accessible by the derived class, that means not that they are inacessible, but that they must be modified via the class public/private methods, and not through direct assignment.
For privately derived classes, only those data members and member functions that are defined (or overridden) in the derived class can be accessed. Member functions of a privately derived class can access the base class's data members and member functions, but users of objects of the derived class cannot used the derived objects to access data members and member functions of the base class. In other words, public inheritance is used to define subtypes (which can also share behavior), while private inheritance allows sharing of behavior, but does not permit an instance of the derived class to be used in situations where a base class instance would be expected.
| - | the base class constructor is run before the derived class constructor is run |
| - | initial values may be supplied for the base class object with a member initialization list: |
base-derived-derived-base
Possible in C++ but not in java.
| Leave a Reply |