Professional Documents
Culture Documents
Chapter 4 Inheritance
Chapter 4 Inheritance
com)
44
Inheritance
Syllabus
Concepts of inheritance, Derived classes, Member declaration (Protected), Types of
inheritance (Single, multilevel, multiple, hierarchical, Hybrid inheritance), Virtual
base classes, Abstract classes, Constructors in derived classes, Member classes.
Inheritance
Q1.What is inheritance state its purpose ?
Ans. The mechanism of deriving a new class from an old class is called inheritance.
Inheritance provides the concept of reusability. The C++ classes can be reused using
inheritance.
In C++, the classes can be reused in several ways. The already written, tested class
can be reused by using properties of the existing ones. This is achieved by creating new
classes from the existing one. This mechanism is known as Inheritance.
The old class is referred as Base, Super or parent class whereas the new class is
called as derived , child or sub class.
Features or Advantages of Inheritance
1. Reusability
Inheritance helps the code to be reused in many situations. The base class
is defined and once it is compiled, it need not be reworked. Using the concept of
inheritance, the programmer can create as many derived classes from the base
class as needed while adding specific features to each derived class as needed.
2. Saves Time and Effort
The above concept of reusability achieved by inheritance saves the programmer
time and effort. Since the main code written can be reused in various situations as
needed.
3. Increases Program Structure which results in greater reliability.
4. Polymorphism
Q2.What is not inherited from the base class?
Ans. In principle, a derived class inherits every member of a base class except:
Public :
int d ;
int y ;
Public :
int q ;
void disp();
//Base class
//derived class
Syntax:
Class A
{ . . . . . . };
Class B: private/public A
{ ------- };
Consider the example of single inheritance as shown in above figure. The
class A is the base class while class B is the derived class. Class A contains one
private member and one public data member and one public data member with three
member functions. Class B contains one private data member and two public
member functions.
Class B is publicly inherited from class A. Therefore class B has all the
public members of class A in the public section of class B. The private members of
class A cannot be inherited in effect class B and has one public data member and five
member functions along with one private data member.
Class A
{
int a;
public:
int b;
void getd();
void disp();
int geta()
{
return (a)
}
};
4
}
void B::display_b()
{
cout << "b = " << b << "\n";
}
/*----------------------Class definitions ends here---------------*/
void main(void)
{
B obj;
// accessing public member function of the base directly
obj. read _n1(100);
obj. read _n2_and_b(200,300);
// accessing public member function of the base directly
obj.display_n1n2();
obj.display_b();
}
Output
a1 = 100
a2 = 200
b = 300
Explanation
ClassA is declared to have one private data member n1 and three members,
n2(data) and set_nl() and display_n1n2() which are the member functions. set_n1() is
used to initialise al which is a private data member and cannot be directly accessed.
Class B inherits A publically. That means all the public members of A are directly
accessible to the objects of B. The member function set_n2_andb() initialise b, its own
private member and public member n2 of the base.
The public members of the base remains the public members of the derived or
extended class B as the public visibility mode is used in the derivation inheritance. One
can access the public member of the base class through the object of the derived class.
Q8.Program to demonstrate Single Inheritance
Ans.
#include <iostream.h>
#include <conio.h>
class Value
{
protected:
int val;
public:
void set_values (int a)
{
6
}
Q12.Describe how private members are inherited
Ans.Private members of base class cant be inherited. Therefore class cant achieve the
properties of private data members. If we have to derive private members we have to
make it accessible to all other functions. Thus eliminating the advantage of data hiding
concept.
C++ provides another visibility modifiers that are protected. Which saves
unlimited purpose in inheritance. A member declared as protected is accessible by the
member function within its class and any class immediately derived from it. It cant be
accessed by the function outside these two classes. A class can have all the visibility
modes shown below.
Class ABC
{
private:
//visibility within class
---------------------------------------Protected: //visibility within class & immediate derived class.
---------------------------------------Public:
//Visible in function program
---------------------------------------};
When a protected member is inherited in public mode. It becomes protected in
derived class & accessible by the member function of the derived class. It is also ready
for further inheritance. Protected members inherited in the private mode become the
private data members in the derived class. It is available for the member function of
class but not inherited for further inheritance.
Base
class Derived class
visibility
Privately Inheritance
Private
Non inherited
Protected
Private
Public
Private
Publicly Inherited
Not inherited
Protected
Public
10
};
// B as an inheritance of A
class B : private A
// private derivation
{
int b;
// private data member
public :
void set(int, int, int);
// public member functions
void display();
};
/*----------------------implementation of complete Class ---------------------*/
// member function definitions for class B
void B::set(int x, int y, int z)
{
// accessing the protected member of the class
a1=x;
// accessing the public member of the class
a2=y;
// accessing own private member as usual
b = z;
}
void B::display()
{
// accessing the protected member of the class
cout << "a1 = " << a1 << "\n";
// accessing the public member of the class
cout << "a2 = " << a2 << "\n";
// accessing the private member of the class
cout << "b = " << b << "\n";
12
};
// B as an inheritance of A
13
17
Overriding
1.Different functions
different class.
have
same
Multilevel Inheritance
Super
Base
B1
B2
B3
22
University
Arts
Medical
Engg.
CM
IF
27
Class grandparent
Parent
{
};
class parent1 : virtual public grandparent
Parent2
Parent1
{
};
class parent2 : private virtual grandparent
Child
{
};
When a class is made virtual base class C++ takes necessary care to see
that only one copy of class is inherited regardless of how many inherited paths exist.
Q34.Write Program to demonstrate Virtual Base Class in c++
Ans. Program to demonstrate Virtual Base Class
#include<iostream.h>
#include<conio.h>
35
Sport
The derived class takes the responsibility of supplying the initial values to its base
class. The constructor of the derived class receives the entire list of required
values as its argument and passes them on to the base constructor in the order in
which they are declared in the derived class. A base class constructor is called
and executed before executing the statements in the body of the derived class.
The header line of the derived-constructor function contains two parts separated
by a colon (:). The first part provides the declaration of the arguments that are
passed to the derived class constructor and the second part lists the function calls
to the base class.
Example: D(int a1, int a2, int b1, int b2, int d): A(a1, a2), B(b1, b2)
{
o d = d1;
}
40
A(a1, a2) invokes the base constructor A() and B(b1, b2) invokes another base
class constructor B(). The constructor D() supply the values i.e. a1, a2, b1, b2 (to
A() and B()) and to one of its own variables d1.
Hence, the assignment of the values will be as follows:
When an object of D is created, D object-name(5, 12, 7, 8, 30);
a1 <- 5 a2 <- 12 b1 <- 7 b2 <- 8 d1 <- 30
The constructors for a virtual base class are invoked before any non-virtual base
classes. If there are multiple virtual base classes, then they are invoked in the
order in which they are declared.
Method Of Inheritance
Class A: public b
{
}
Class A: public b,Public c
{
}
class A : private c, virtual public d
{
}
Order Of Execution
B
A
B
C
A
B
C
D
A
//destructor
};
45
//destructor
};
class derivedC : public derivedB
{
public:
~derivedC() ;
//destructor
};
class derivedD : public derivedC
{
public:
46
//destructor
};
baseA::~baseA()
{
cout<< \nbaseA class destructor;
}
derivedB::~derivedB()
{
cout<< \nderivedB class destructor;
}
derivedC::~derivedC()
{
cout<< \nderivedC class destructor;
}
derivedD::~derivedD()
{
cout<< \nderivedD class destructor;
}
void main()
{
derviedD objD();
}
output of program
derivedD class
derivedC class
derivedB class
base class
Nested Class or Container Class
Q43.Describe what is member class ? or nesting of class
Ans.Inheritance is the mechanism of driving certain properties of one class into another
class. C++ supports another way of inheriting the properties of one class into another
that is a class can contain the object of another class as its member. I.e. an object can
be collection of other objects.
A nested class is declared within the scope of another class. The name of a nested
class is local to its enclosing class. Unless you use explicit pointers, references, or object
names, declarations in a nested class can only use visible constructs, including type
names, static members, and enumerators from the enclosing class and global variables.
47
Class B
C c1;
B is kind of A
B has object of C
// Inheritance
//Containership
One can define member functions and static data members of a nested class in
namespace scope. For example, in the following code fragment, you can access the static
members x and y and member functions f() and g() of the nested class nested by using a
qualified type name. Qualified type names allow you to define a typedef to represent a
qualified class name. You can then use the typedef with the :: (scope resolution) operator
to refer to a nested class or class member, as shown in the following example:
Example code
class outside
{
public:
class nested
{
public:
static int x;
static int y;
48
Member Variable :
Subject Name
Member Variable :
MemberShip No
59
Ans,
Class Student
{
int Rollno;
char name[40];
public :
void getStudent( int rn , char nm[])
{
Rollno = rn;
Strcpy(name,nm);
}
void displayStudent()
{
cout<< \nName =<<name;
cout << \n Roll Number =<<Rollno;
}
};
Class Exam : public Student
{
char subject_name[40];
public :
void getExam( char snm[])
{
Strcpy(subject_name,snm);
}
void displayExam()
{
cout<< \nName of subject =<<subject_name;
}
};
Class Library: public Student
{
int membership_no;
public :
void getLibrary (int mmno)
{
membership_no = mmno;
}
void displayLibrary()
{
cout<< \MemberShip Number =<<membership_no;
60
Program-2
Write a program for following hierarchy inheritance in the given fig. Assume suitable
member function
Staff Code
Teacher Subject
Officer grade
Ans.
Class Staff
{
int staffcodeno;
char staffname[40];
public :
void getStaffDetails( int sfc , char snm[])
{
staffcodeno = sfc;
Strcpy(staffname,snm);
}
void displayStaff()
{
cout<< \nName of Staff =<<staffname;
cout << \n Code Number of Staff =<<staffcodeno;
}
};
Class Teacher : public Staff
61
Customer
int phone;
char cname[40];
Name
public :
Phone_No
void getCustomer( int ph , char cnm[])
{
Phone = ph;
Strcpy(name,nm);
Depositor
}
Acc_no
void displayCustomer ()
Balance
{
cout<< \nCustomer Name =<<cname;
cout << \n Customer Phone Number =<<Rollno;
}
Borrower
};
Class Depositor : public Customer
Loan_no
{
Loan_amm
int accno;
int balance;
public :
void getDepositor(int ano , int bal)
{
accno = ano;
balance = bal;
}
void displayDepositor()
{
cout << \n Account Number =<<accno;
cout << \n Balance Amount =<< bal;
}
};
Class Borrower: public Depositor
{
int Loanno;
int Loanamt;
public :
void getBorrower(int lno , int lamt)
{
Loanno = lno;
Loanamt= lamt;
}
void displayBorrower()
63
Teacher Subject
Officer grade
Depositor
Acc_no
Balance
Borrower
Loan_no
Loan_amm
67
Summer 2009
a. What is inheritance ? Mention and explain three types of inheritance you know.
b. Explain multilevel inheritance with suitable example program.
Winter 2009
a. What does inheritance means in C++? Describe syntax of single inheritance.
b. When do we make a class virtual? What is an
abstract class?
c. What is meant by overloading and overriding?
d. Write a program that illustrate multiple
inheritance
e.
Summer 2010
a. What does inheritance means in c++?Describe
syntax of Single Inheritance
b. When do we make virtual base class? Explain
with suitable example.
c. What is meant by overloading and overriding
d. Identify Inheritance shown in following Figure
No. 1 Implement it by using suitable memberfunction
68