21
www.edutechlearners.com Page 1 Base classes and Derived Classes An object of one class is an object of another class, as well. For example, in geometry, a rectangle is a quadrilateral. Thus, in C++ class rectangle can be said to inherit from class Quadrilateral. In this context, class Quadrilateral is a base class, and class Rectangle is a derived class. A rectangle is a specific type of quadrilateral, but it is incorrect to claim that a quadrilateral is a rectangle – the quadrilateral could be a parallelogram or some other shape. Every derived – class object is an object of its base class, and one base class can have many derived classes, the set of objects represented by a base class typically is larger than the set of objects represented by any of its derived classes. For example, the base class vehicle represent all vehicles, including cars, trucks, boats, airplanes, bicycles and so on. By contrast, derived class Car represents a smaller, more specific subset of all vehicles. Protected Members Using protected access offers an intermediate level of protection between public and private access. A base class’s protected members can be accessed with the body of that base class, by members and friends of that base class, and by members and friends of any classes derived from that base class. Derived – class member functions can refer to public and protected members of the base class simply by using the member names. When a derived class member function redefines a base class member function, the base class member can be accessed from the derived class by preceding the base class member name with the base-class name and the scope resolution operator(::). When we declared base class data members as protected, so derived classes can modify the data directly. Inheriting protected data members slightly increases performance, because we can directly access the members without incurring the overhead of calls to get and display member functions. Using protected data members creates two serious problems. First, the derived class object does not have to use a member function to get the value of the base class’s protected data member. Therefore, a derived-class object easily can assign an invalid value to the protected data member, thus leaving the object in an inconsistent state. The second problem with using protected data members is that derived – class member functions are more likely to be written so that they depend on the base – class implementation. In practice, derived classes should depend only on the base – class services and not on the base – class implementation. With protected data members in the base class, if the base – class implementation changes, we may need to modify all derived classes of that base class. Types of Derivation (Inheritance) Inheritance is a process of creating a new class from an existing class. While deriving the new classes, the access control specifier gives the total control over the data members and methods of the base classes. A derived class can be defined with one of the access specifiers, i.e. private, public and protected. Public Inheritance In a public derivation Each public member in the base class is public in the derived class. Each protected member in the base class is protected in the derived class. Each private member in the base class remains private in the base class and hence it is visible only in the base class (not inherited).

Base classes and Derived Classes - EduTechLearners · Base classes and Derived Classes An object of one class is an object of another class, as well. For example, in geometry, a rectangle

  • Upload
    others

  • View
    20

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Base classes and Derived Classes - EduTechLearners · Base classes and Derived Classes An object of one class is an object of another class, as well. For example, in geometry, a rectangle

www.edutechlearners.com Page 1

Base classes and Derived Classes An object of one class is an object of another class, as well. For example, in geometry, a rectangle is a quadrilateral. Thus, in C++ class rectangle can be said to inherit from class Quadrilateral. In this context, class Quadrilateral is a base class, and class Rectangle is a derived class. A rectangle is a specific type of quadrilateral, but it is incorrect to claim that a quadrilateral is a rectangle – the quadrilateral could be a parallelogram or some other shape. Every derived – class object is an object of its base class, and one base class can have many derived classes, the set of objects represented by a base class typically is larger than the set of objects represented by any of its derived classes. For example, the base class vehicle represent all vehicles, including cars, trucks, boats, airplanes, bicycles and so on. By contrast, derived class Car represents a smaller, more specific subset of all vehicles. Protected Members Using protected access offers an intermediate level of protection between public and private access. A base class’s protected members can be accessed with the body of that base class, by members and friends of that base class, and by members and friends of any classes derived from that base class. Derived – class member functions can refer to public and protected members of the base class simply by using the member names. When a derived class member function redefines a base class member function, the base class member can be accessed from the derived class by preceding the base class member name with the base-class name and the scope resolution operator(::).

When we declared base class data members as protected, so derived classes can modify the data directly. Inheriting

protected data members slightly increases performance, because we can directly access the members without

incurring the overhead of calls to get and display member functions. Using protected data members creates two serious problems. First, the derived class object does not have to use a member function to get the value of the base class’s protected data member. Therefore, a derived-class object easily can assign an invalid value to the protected data member, thus leaving the object in an inconsistent state. The second problem with using protected data members is that derived – class member functions are more likely to be written so that they depend on the base – class implementation. In practice, derived classes should depend only on the base – class services and not on the base – class implementation. With protected data members in the base class, if the base – class implementation changes, we may need to modify all derived classes of that base class. Types of Derivation (Inheritance) Inheritance is a process of creating a new class from an existing class. While deriving the new classes, the access control specifier gives the total control over the data members and methods of the base classes. A derived class can be defined with one of the access specifiers, i.e. private, public and protected. Public Inheritance In a public derivation • Each public member in the base class is public in the derived class. • Each protected member in the base class is protected in the derived class. • Each private member in the base class remains private in the base class and hence it is visible only in the base

class (not inherited).

Page 2: Base classes and Derived Classes - EduTechLearners · Base classes and Derived Classes An object of one class is an object of another class, as well. For example, in geometry, a rectangle

www.edutechlearners.com Page 2

Private Inheritance In a private derivation • Each public member in the base class is private in the derived class. • Each protected member in the base class is private in the derived class. • Each private member in the base class remains private in the base class and hence it is visible only in the base

class (not inherited). Protected Inheritance In a protected inheritance • Each public member in the base class is protected in the derived class. • Each protected member in the base class is protected in the derived class. • Each private member in the base class remains private in the base class and hence it is visible only in the base

class (not inherited). Multiple Inheritance Multiple inheritance is the process of creating a new class from more than one base classes. Multiple inheritance is a derived class declared to inherit properties of two or more base classes. Multiple inheritance can combine the behavior of multiple base classes in a single derived class. Multiple inheritance has many advantages over single inheritance such as rich semantics and the ability to directly express complex structures. In C++, derived classes must be declared during the compilation of all possible combinations of derivations and the program can choose the appropriate class at run time and create object for the application. ( in short, in multiple inheritance, a derived class has multiple base classes.). Member access control It is well known that the C++ class is more than an enhanced version of the C structure. In this section, access control and its mechanism to access the individual members of a class as well as derived class are explained. It has already been stated that the access mechanism of the individual members of a class is based on the use of the keywords public, protected and private. Accessing the Public Data The public members of a class can be accessed by the following:

• Member functions of the class. • Non-member functions of the class (through object). • Member functions of a friend class • Member functions of a derived class. • Friend functions of the class.

Accessing the Private Data The private members of a class can be accessed only by the followings:

• The member function of the class, and • The member functions of the friend class. • The friend functions of the class.

Page 3: Base classes and Derived Classes - EduTechLearners · Base classes and Derived Classes An object of one class is an object of another class, as well. For example, in geometry, a rectangle

www.edutechlearners.com Page 3

Accessing the Protected Data • The member functions of the class. • Member functions of a friend class. • Member function of a derived class. • The friend functions of the class.

Casting Base Class Pointers to Derived Class Pointers Pointers are also central to polymorphism in C++. To enable polymorphism, C++ allows a pointer in a base class to point to either a base class object or to any derived class object. By contrast, a pointer to derived class object may not point to a base class object without explicit casting. Suppose A is the base class for the class B. Any pointer to A type (base class) can be assigned the address of an object of the class B (Derived class). In addition to the address of an object of its own class, i.e., pointers of objects of base class are type –compatible with pointers to objects of derived class. A a, *ap; ap = &a; The pointer ap is made to point to a, an object A type. This is quite obvious. All the public members of the class can be accessed through ap with the help -> operator. If display() is a member function of the class, ap -> display(); is a valid statement. B b; The C++ language permits the pointer ap to be able to point to b also using the assignment ap = &b;. Even though this is possible the public members of the class B can not be accessed through ap. Suppose the class B also has the member function by name display(), even the ap -> display(); refers to the function in the base class A itself. Selection of the public members through the pointer ap depends on the type of the pointer rather than the content of the pointer. Program: Casting of Base Class Pointers to Derived Class Pointer (without virtual functions) #include<iostream.h> class alpha {

protected: int a;

public: alpha ( int a = 0 ) { a = i; }

void display () { cout << “ a = “ << a << “\n”;

} };

Page 4: Base classes and Derived Classes - EduTechLearners · Base classes and Derived Classes An object of one class is an object of another class, as well. For example, in geometry, a rectangle

www.edutechlearners.com Page 4

class beta : public alpha { private : int b; public: beta (int j = 0) { b = j;

}; void display( ) { cout << “b = “ << b << “\n”; }

}; int main( ) { alpha a1(10), *ap; beta b1(20); ap = &a1; ap -> display(); ap = &b1;

ap -> display(); return 0;

} input – output: a = 10; a = 10; Explanation In Program, alpha is the base class and beta is its derived class. The member function display() in alpha and the same named function is defined even within the derived class beta. The pointer to base type (alpha) ap is made to point to a1. An object of alpha type, ap -> display(); is then invoked to display the member data of a1. The display() is from the base class alpha. The same pointer is assigned the address of the object b1. The display() is from the base class alpha. It has been observed that the member function selected for the execution depends on the type of pointer (i.e base class or derived class) rather than the content of pointer ( &a1 or &b1). During the Compilation time, the compiler determines which function is used based on the type of pointer. The compiler substitute the correct function for each invocation. The function calls are resolved during the runtime of the program and hence the phenomenon is called compile-time polymorphism or early binding or static binding. Casting of Base Class Pointers to Derived Class Pointer (with virtual functions) How do we use a pointer to base type to access the public members of the base class when it is made to point to an object of the base type, and to access the public members of the derived class when it is made to point to an object of the derived type? This is where the concept of virtual functions comes into picture. This objective is achieved by using the keyword virtual in the header of the base class function.

Page 5: Base classes and Derived Classes - EduTechLearners · Base classes and Derived Classes An object of one class is an object of another class, as well. For example, in geometry, a rectangle

www.edutechlearners.com Page 5

Program: Casting of Base Class Pointers to Derived Class Pointer (with virtual functions) #include<iostream.h> class alpha { protected: int a; public: alpha ( int a = 0 ) { a = i;

} virtual void display ( ) { cout << “ a = “ << a << “\n”;

} }; class beta : public alpha {

private : int b;

public: beta (int j = 0) { b = j;

} }; void display( ) { cout << “b = “ << b << “\n”; }

}; int main( ) {

alpha a1(10), *ap;

beta b1(20); ap = &a1; ap -> display();

ap = &b1;

ap -> display(); return 0;

} input – output: a = 10; b = 20;

Page 6: Base classes and Derived Classes - EduTechLearners · Base classes and Derived Classes An object of one class is an object of another class, as well. For example, in geometry, a rectangle

www.edutechlearners.com Page 6

Explanation:- In Program, alpha is the base class and beta is its derived class. The member function display() in alpha is made virtual and the same named function is defined even within the derived class beta. The pointer to base type (alpha) ap is made to point to a1. An object of alpha type, ap -> display(); is then invoked to display the member data of a1. The display() is from the base class alpha. The same pointer is assigned the address of the object b1. The display() is from the derived class beta. This has been made possible because the same named function in the base class alpha has been made virtual. As can be observed from Program, the member function selected for execution depends on the content of the pointer rather than the type of the pointer. The function calls are resolved during the runtime of the program and hence the phenomenon is called runtime polymorphism or late binding or dynamic binding. Private Inheritance When class B is derived from the class A publicly (i.e., with the line class B : public A in the definition of B), we know that the protected and the public members of the class A are accessible in the class B and also an object of derived class B can access all the public members of the base class A outside the class. Consider the following class definition: class B : private A { }; Here the class B is said to be privately derived from the class A. All the protected and public members of the base class A are accessible in the derived class B. But an object of the class B can not access even the public members of the base class A also. The protected and public members of the base class will become the private members of the derived class. The functionality of the base class A is hidden in the derived class B. But there is a way out for making only some public member functions of the base class accessible to objects of derived class, i.e., by using the base class name followed by the :: followed by the function name in the public section of the derived class. Consider the following code: class alpha {

protected: int j; public: int k; };

class beta : private alpha {

public: void set ( ) {

j = 20; k = 30; }

void display( ) { cout << “within display() of beta \n”; cout << “ j = “ << j; cout << “k = “ << k;

} };

Page 7: Base classes and Derived Classes - EduTechLearners · Base classes and Derived Classes An object of one class is an object of another class, as well. For example, in geometry, a rectangle

www.edutechlearners.com Page 7

class gamma : private beta { public: void show ( ) {

cout << “within show of gamma \n”; cout<<” j = “ << j; //error cout << “k = “ << k; //error }

} int main( ) {

beta b; b.display();

gamma g; g.show(); } The class alpha has a protected member j and public member k of int type. The class beta is privately derived from the class alpha. As a result, both j and k of alpha class become private members of beta class. Within the beta class, the member function set() assigns values to both j and k and the member function display() displays the values of both j and k. The class gamma is derived from beta. Within gamma the members j and k can not be accessed. An attempt to display them through show() of gamma class would thus fail. The line of code beta::display(); in the public section of gamma makes the display() of beta be accessible with an object of gamma class if g is an object of gamma class then g.display(); would be a valid function call. Protected Inheritance Now, consider the following definition: class b : protected a { }; Here the class B is said to be protectedly derived from the class A. All the protected and public members of the base class A would now become protected members of the derived class B and hence they can be accessed with the class B and in any other class which is derived from B. No members of the class A can be accessed by an object of class B. Consider the following code: class alpha { protected: int j;

public: int k; };

Page 8: Base classes and Derived Classes - EduTechLearners · Base classes and Derived Classes An object of one class is an object of another class, as well. For example, in geometry, a rectangle

www.edutechlearners.com Page 8

class beta : protected alpha {

public: void set ( ) {

j = 20; k = 30;

} void display( ) {

cout << “within display() of beta \n”; cout << “ j = “ << j; cout << “k = “ << k; }

}; class gamma : protected beta { public: void show ( ) {

cout << “within show of gamma \n”; cout<<” j = “ << j; cout << “k = “ << k;

} } int main( ) {

beta b;

b.display( ); gamma g; g.show( ); }

The class alpha has a protected member j and public member k of int type. The class beta is protectedly derived from the class alpha. As a result, both j and k of alpha class become protected members of beta class. Within the beta class, the member function set() assigns values to both j and k and the member function display() displays the values of both j and k. The class gamma is derived from beta. Within gamma the members j and k can stil be accessed. The member function show() of gamma display both the values. Public Inheritance Now, consider the following definition: class b : public a { }; Here the class B is said to be publicly derived from the class A. All the protected and public members of the base class A would remain same members of the derived class B and hence they can be accessed with the class B and in any other class which is derived from B. public members of the class A can be accessed by an object of class B whereas the protected

Page 9: Base classes and Derived Classes - EduTechLearners · Base classes and Derived Classes An object of one class is an object of another class, as well. For example, in geometry, a rectangle

www.edutechlearners.com Page 9

members of the class A can not be accessed by an object of class B. Consider the following code: class alpha { protected: int j;

public: int k; };

class beta : public alpha {

public: void set ( ) {

j = 20; k = 30;

}

void display( ) {

cout << “within display() of beta \n”; cout << “ j = “ << j; cout << “k = “ << k; }

}; class gamma : public beta { public: void show ( ) { cout << “within show of gamma \n”; cout<<” j = “ << j; cout << “k = “ << k;

} } int main( ) { beta b;

b.display(); gamma g; g.show();

cout<<” j =” << j ; //error cout << “ k = “ << k;

} The class alpha has a protected member j and public member k of int type. The class beta is publicly derived from the class alpha. As a result, both j and k of alpha class remains same members of beta class. Within the beta class, the member function set() assigns values to both j and k and the member function display() displays the values of both j and k.

Page 10: Base classes and Derived Classes - EduTechLearners · Base classes and Derived Classes An object of one class is an object of another class, as well. For example, in geometry, a rectangle

www.edutechlearners.com Page 10

The class gamma is derived from beta. Within gamma the members j and k can still be accessed. The member function show() of gamma display both the values. But direct access through object of class gamma is possible only for k not for j ; Accessibility of Base Class Members in Derived Classes The following table depicts the accessibility of the base class members with different access specifiers in the derived classes when derived publicly, privately and protectedly. Base Class Access Mode

Derived class access mode

Public Public private Protected

Private Not inheritable

Not inheritable

Not inheritable

protected protected Private Protected

Access Specifier Class

Accessible From own Class Outside

Accessible From Derived Class

Accessible From others

Public YES YES YES

Private YES NO NO

Protected YES YES NO

Constructors, Destructors and Inheritance We know that constructor and destructor for a class are special member functions for the class. They are invoked implicitly for the objects of the class. Constructor gets invoked implicitly and helps in creating objects (i.e. allocating the required amount of memory for the member data and setting values for them and destructor for a class implicitly when an object of the class goes out of scope and destroys the object thereby releasing the block of memory occupied by the object. When we make a class (derived class) inherit the functionality of another class (base class) each provided with constructor and destructor, since we instantiate objects of the derived class. It is interesting to note the order of execution of constructor and destructor in base class and of those in derived class. When an object of derived class is declared, constructor of the base class gets executed first and then the constructor of the derived class gets executed. But, the order of execution of destructor of base class and derived class is reverse. When the object goes out of scope, the destructor of derived class gets executed and that is followed by the destructor of the base class.

Page 11: Base classes and Derived Classes - EduTechLearners · Base classes and Derived Classes An object of one class is an object of another class, as well. For example, in geometry, a rectangle

www.edutechlearners.com Page 11

Program: Single level inheritance #include<iostream.h> #include<conio.h> class alpha { public: alpha() { cout << “constructor in alpha class \n”; }

~alpha() { cout << “destructor in alpha class \n”; }

}; class beta : public alpha { public: beta( ) { cout << “constructor in beta class \n”; }

~beta( ) { cout << “destructor in beta class \n”;

} }; int main( ) { beta b; return 0;

} input-output:

constructor in alpha class

constructor in beta class

destructor in beta class

destructor in alpha class Explanation In Program, the class alpha is defined with a constructor and destructor. The statement cout << “constructor in alpha class \n”; in the body the constructor is to display the string “Constructor in alpha class \n” on the screen while the constructor of the alpha class gets executed. The statement cout << “ destructor in alpha class \n”; in the body the destructor is to display the “destructor in alpha class \n” on the screen while the destructor of the alpha class gets executed.

Page 12: Base classes and Derived Classes - EduTechLearners · Base classes and Derived Classes An object of one class is an object of another class, as well. For example, in geometry, a rectangle

www.edutechlearners.com Page 12

The class beta is derived from the class alpha and it is also has a constructor and destructor. The statement cout<< “constructor in beta class \n”; in the body the constructor is to display the string “constructor in beta class \n” on the screen while the constructor of the beta class gets executed. The statement cout <<”destructor in beta class \n”; in the body the destructor is to display the string “destructor in beta class \n” on the screen while the destructor of the beta class gets executed. In the main(), b is declared to be an object of beta type. During the process of its creation, the constructor in the base class (alpha) is executed and then the constructor of the derived class (beta) gets executed. This is evident from the order of display of the strings “constructor in alpha class” and “constructor in beta class” in the output of the program. When the object goes out of scope, the destructor in the derived class beta gets executed and it is followed by the execution of the destructor in the base class alpha. This is evident from the order of display of the strings “destructor in alpha class” and “destructor in beta class”. Overloaded Constructors in Single Level Inheritance In the previous program, both base class and the derived class had only default constructor. We may have overloaded constructors in both the classes. If the base class contains only default constructor and derived class contains overloaded constructors, during the creation of all objects of the derived class with of without arguments (initial values), the default constructor in the base class gets executed and then the corresponding constructor in the derived class get executed. What if the constructors in the base class are overloaded? How can we select the required constructor of the base class for execution? Program enlightens on this. Program: To illustrate Overloaded Constructors in Single Level Inheritance #include <iostream.h> #include <conio.h> class alpha {

protected: int i; public:

alpha() { i = 10; } alpha (int l) { i = l ;

} }; class beta : public alpha { private: int j; public: beta( ) { j = 20; }

Page 13: Base classes and Derived Classes - EduTechLearners · Base classes and Derived Classes An object of one class is an object of another class, as well. For example, in geometry, a rectangle

www.edutechlearners.com Page 13

beta (int m) { j = m; }

beta( int m, int n) : alpha(m) { j = m; }

void display() { cout << “i = “ << i ; cout << “ j =” << j; }

}; int main() { clrscr() beta b1, b2(30), b3(40,50); cout<< “ members data of b1”; b1.display();

cout << “members data of b2”; b2.display(); cout << “members data of b3”; b3.display(); return 0;

} input – output: members data of b1 10 20

members data of b2 10 30

members data of b3 40 50 Explanation In program, the class alpha is defined with a protected member data I , a constructor without arguments and a constructor with one argument. The class beta is derived from the class alpha and it has its own private member data j of int type, a constructor without any arguments, a constructor with one argument and another constructor with two arguments. In the main(), b1 is declared to be an object of beta type without any initial value. During its creation, the default constructor in the base class (alpha) gets executed and then the default constructor in the derived class (beta) gets executed. As a result of which, the member data I of alpha gets the value 10 and the member data j of beta gets the value 20. B2 is declared to be an object of beta type with one initial value 30. During its creation, the default constructor in the base class (alpha) gets executed and then the constructor with one argument in the derived class (beta) gets executed. As a result of which, the member data I of alpha gets the value 10 and the member data j of beta gets the value 30. B3 is declared to be an object of beta type two arguments 40 and 50. Note the definition of the constructor with two arguments. In the header of the constructor, the constructor with one argument of alpha class is invoked with the first formal parameter of the beta class constructor as the actual argument for the alpha class constructor. During its creation, the constructor with one argument in the base class (alpha) gets executed and then

Page 14: Base classes and Derived Classes - EduTechLearners · Base classes and Derived Classes An object of one class is an object of another class, as well. For example, in geometry, a rectangle

www.edutechlearners.com Page 14

the constructor in the derived class (beta) gets executed. As a result of which, the member data I of alpha gets the value 40 and the member data j of beta gets the value 50. The member data of all the three objects are then displayed. Constructor, Destructors in Multiple Inheritance Program: Constructors, Destructors in Multiple Inheritance #include<iostream.h> #include<conio.h> class alpha {

public: alpha ( ) {

cout << “constructor in alpha class \n”; } ~ alpha( ) ~ { cout<< “ destructor in alpha class”;

} }; class beta { public: beta() { cout << “constructor in beta class \n”; }

~beta() { cout << “destructor in beta class \n”; }

}; class gamma : public alpha, public beta { public: { gamma( ) {

cout << “constructor in gamma class \n”; }

~gamma( ) { cout<< “destructor in gamma class \n”; }

};

Page 15: Base classes and Derived Classes - EduTechLearners · Base classes and Derived Classes An object of one class is an object of another class, as well. For example, in geometry, a rectangle

www.edutechlearners.com Page 15

int main( ) {

clrscr( ); gamma g; return 0; }

input – output: constructor in alpha class constructor in beta class constructor in gamma class destructor in gamma class destructor in beta class destructor in alpha class

Explanation In Program, the class alpha is defined with default constructor and destructor. The class beta is also defined with default constructor and destructor. The class gamma, which is derived from both alpha and beta, also has its default constructor and destructor. In the body of the default constructor and destructor of each of the classes, an output statement is made to display a string notifying the class name. In the main(), the object g of gamma class is declared. During the course of its creation, as can be seen from the output of the program, the constructor in alpha class (first base class for gamma) gets executed first; then the constructor in beta class (second base class for gamma) gets executed and then the constructor in gamma class gets executed, During the course of the destruction of the object g, the destructor in gamma class gets executed, followed by the execution of the destructor in beta class, which is then followed by the execution of the destructor in alpha class. Note that the order of execution of destructor in the inheritance hierarchy is opposite to the order of the execution of the constructors. Note: If the line of code class gamma : public alpha, public beta is replaced with the line of code class class gamma : public alpha, virtual public beta, the order of execution of alpha and beta class constructors and destructors is reversed. However, the gamma class constructor and destructor get executed as in the earlier case. Implicit Derived – Class Object to Base – Class Object Conversion (Object Slicing) If A is a class and B is another class derived from the class A, we can assign an object of B type and an object of A type (however, the reverse assignment is not permissible) and this assignment lead to a phenomenon called object slicing. #include<iostream.h> #include<conio.h> class alpha { protected: int i; public: alpha() { i = 10;

}

Page 16: Base classes and Derived Classes - EduTechLearners · Base classes and Derived Classes An object of one class is an object of another class, as well. For example, in geometry, a rectangle

www.edutechlearners.com Page 16

void display() { cout << “ i =” << i << “\n”;

} ~alpha() { }

}; class beta : public alpha {

private: int j; public: beta () : alpha() { j = 20;

} void display() { alpha :: display(); cout << “ j =” << j << “\n”; } ~beta() { }

}; int main( ) { clrscr(); alpha a; beta b;

cout << “size of a” << sizeof(a) << “\n”; a.display();

cout << “size of b” << sizeof(b) << “\n”; b.display(); a = b ; //object slicing cout << “size of a” << sizeof(a) << “\n”;

a.display(); getch(); return 0;

} input – output: size of a 2 i =10 size of b 4 10 20 size of a 2 i = 10

Page 17: Base classes and Derived Classes - EduTechLearners · Base classes and Derived Classes An object of one class is an object of another class, as well. For example, in geometry, a rectangle

www.edutechlearners.com Page 17

Explanation In Program, the class alpha is defined with an integer member data I , a constructor to initialize the member data of the objects of the class, a member function display() to display the member data values of the objects of the class and destructor. The class beta is derived from the class alpha and it contains its own member data j of int type, a constructor and display() to display the member data of the objects of the class. Note that there is a call to display() of alpha class. In the main(), a and b are declared to be objects or type alpha and beta respectively, The size and values of both the objects are displayed. Note that the size of a is two and that of b is four. This is because the object a of alpha class has one member data of int type and the object b of beta class has two member data of int type (one of itself and the other of its base class alpha). The statement a = b ; assigns the object b of beta type to the object a of alpha type. The object b has two integer values (its member data j and the inherited member data I of alpha class) associated with it as already mentioned. But the assignment assigns only inherited member data to a, since the object a cannot accommodate both the members of b. This effect is called object slicing. Here, the object b is said to have been sliced when it is assigned to the object a of alpha type.

Note: Assignment of a derived class object to a base class object is possible. But the converse is not permitted, Composition (Containership and Delegation) The containership is another way of reusing existing code. In this case objects of one class are made the members of another class. Suppose A is a class and a is an object of the class. In another class, say B the object a can be made a member. As a result of this, the code in the class A is reused in the class B as well. Since the class B contains an instance of class A, it is said to explicit “Has a Relationship”. It is also said that the class A has delegated some responsibility to the object b and, thus, exhibits delegation phenomenon. Program: To illustrate Containership #include<iostram.h> class time {

private: int h, m, s; public: void get();

void display();

}; void time :: get() {

cout << “enter hours, minutes and seconds \n”; cin >> h >> m >> s; }

void time :: display () { cout << h << “:” << m << “:” << s << “\n”; }

class date {

private: int d, m, y; time t;

Page 18: Base classes and Derived Classes - EduTechLearners · Base classes and Derived Classes An object of one class is an object of another class, as well. For example, in geometry, a rectangle

www.edutechlearners.com Page 18

public: void get();

void display(); };

void date :: get() {

cout << “enter day, month and year \n”; cin >> d >> m >> y; t.get(); }

void date :: display() { cout << d << “/” << m << “/” << y << “\n”; t.display(); }

int main( ) { date dt; dt.get(); dt.display(); return 0; }

input – output: enter day, month and year 12 01 1863 enter hours, mintues and seconds 10 23 45 12/01/1863 10:23:45 Explanation In Program, an object of time is made a member of the class date thereby making the code of time class reusable in the date class. An object of date type comes packages with member data of both time and date classes. The member data of the date class and those of the object t of time type are accepted through the function: void date :: get() { cout <<”enter day, month and year\n”; cin >> d >> m >> y; t.get();

} The member data of the date class and those of the object t of time type are displayed through the function: void date :: display() { cout << d << “/”<<m << “/”<<y<<”\n”; t.display(); }

Page 19: Base classes and Derived Classes - EduTechLearners · Base classes and Derived Classes An object of one class is an object of another class, as well. For example, in geometry, a rectangle

www.edutechlearners.com Page 19

Container Class As we have seen in above example, C++ allows to declare an object of a class as a member of another class. When an object of a class is declared as a member of another class, It is called as a container class. Program: to illustrate container class #include<iostream.h> #include<iomanip.h> class basic_info { private: char name[20]; long int rollno; char sex; public:

void get();

void display(); }; void basic_info :: get() { cout << “enter the name, rollno, sex \n”; cin >> name >> rollno >> sex; }

void basic_info :: display() { cout << “name” << name;

cout << “roll number” << rollno;

cout << “sex” << sex; }

class academic_info { private: char course[20]; char sem[10]; int rank; public:

void get(); void display();

}; void academic :: get() { cout << “enter course, semester and rank”; cin >> course >> sem >> rank;

} void academic_info :: display()

Page 20: Base classes and Derived Classes - EduTechLearners · Base classes and Derived Classes An object of one class is an object of another class, as well. For example, in geometry, a rectangle

www.edutechlearners.com Page 20

{ cout << “course “ << course; cout << “semester” << sem; cout << “rank “ << rank;

} class financial {

private: basic_info bdata;

academic_info acd; float amount; public:

void get(); void display(); };

void financial :: get() { bdata.get(); acd.get();

cout <<”enter amount(rs.)”; cin >> amount; }

void financial :: display() { bdata.display(); acd.display(); cout << setprecision (5); cout << “amount” << amount; }

int main( ) { financial f; cout << “enter the following details”;

f.get(); cout << “ the details is”; f.display(); } input – output: enter name, rollno and sex madhav 222 m enter course, semester and rank b.e. 4th 1 enter amount 25000 name= madav rollno= 222 sex= m course= b.e. rank = 1 amount = 25000 Explanation The program consist of two base classes and one derived class. The base class basic_info contains the data members: name, rollno, and sex. Another base class academic_info contains the data members: course, semester, and rank. The

Page 21: Base classes and Derived Classes - EduTechLearners · Base classes and Derived Classes An object of one class is an object of another class, as well. For example, in geometry, a rectangle

www.edutechlearners.com Page 21

derived class financial contains the data member amount, besides the data members of the base classes. The objects of these two base classes are defined as the data members of the derived class. The member function are used to get information on the derived class and display the contents of the class object. Overriding - Base Class Members in a Derived Class: The phenomenon of ignoring the same named functions in the base class and invoking the same named functions of the derived class whenever an object of the derived class accesses the functions is called Function Overriding. For more details see inheritance. When to Inherit Anytime we build a new class, we should determine whether we can use the preexisting class as a base class. Many a time, we find classes that provide almost the right behavior. These as the candidate classes to inherit from. We can inherit all the desired features and disable the unwanted ones. Disabling the unwanted functions in the base class is done using function overriding. We try to inherit as many features as possible from the already existing classes. This reduces both the size of the program code and the time required for debugging. What can not be inherited? As in real life, even in C++ also not everything can be passed on through inheritance. The following cannot be inherited.

• Constructors • Destructor • User-defined new operators • User-defined assignment operators • Friend relationships