Module 3 - Inheritance An Polymorphism
Module 3 - Inheritance An Polymorphism
6.2 Constructors
• A constructor is a ‘special’ member // class with a constructor
function whose task is to initialize the class integer
data members of an object of its class. {
• It is special because its name is the int m, n; //data members
same as the class name. public:
• The constructor is invoked whenever integer(void); // constructor declared
an object of its associated class is .....
created. .....
• It is called constructor because it };
constructs the values of data members integer :: integer(void) // constructor defined
of the class. {
m = 0; n = 0;
}
The constructor functions have some special characteristics.They are :
• The colon indicates that the derived-class-name is derived from the base-class-name. The visibility-mode is
optional and, if present, may be either private or public. The default visibility-mode is private. Visibility
mode specifies whether the features of the base class are privately derived or publicly derived.
Examples
• When a base class is privately inherited by a derived class, ‘public members’ of
the base class become ‘private members’ of the derived class and therefore the
public members of the base class can only be accessed by the member functions
of the derived class. They are inaccessible to the objects of the derived class.
• On the other hand, when the base class is publicly inherited, ‘public members’ of
the base class become ‘public members’ of the derived class and therefore they
are accessible to the objects of the derived class.
• In both the cases, the private members are not inherited and therefore, the private
members of a base class will never become the members of its derived class.
Single Inheritance
• Refer 8.2 Single public inheritance in online gdb
• And Single private inheritance in online gdb
• Program Explanation:
• The class D is a public derivation of the base class B. Therefore, D inherits all the public members of B and
retains their visibility. Thus, a public member of the base class B is also a public member of the derived class
D. The private members of B cannot be inherited by D.
Public derivation vs Private derivation
Private derivation
Program 8.2 Single inheritance : Private
• Figure 8.5 illustrates how the access control mechanism works in various situations. A simplified view of
access control to the members of a class is shown in Fig. 8.6.
Figure 8.6: A simple view of control to the members of a class
Friend function and friend class
• A friend class can access private and protected members of other
classes in which it is declared as a friend.
• It is sometimes useful to allow a particular class to access private and
protected members of other classes.