You are on page 1of 16

Inheritance

Q:-1 what is Inheritance? Explain Types of Inheritance with example.


The mechanism of deriving a new class from an old one is called inheritance (or
derivation).The old class is referred to as the base class and the new one is called the
derived class or subclass.
Inheritance is a mechanism of reusing and extending existing classes without
modifying them, thus producing hierarchical relationships between them.
Inheritance allows us to define a class in terms of another class, which makes it easier
to create and maintain an application. This also provides an opportunity to reuse the code
functionality and fast implementation time.
There are five types of Inheritance are available
1. Single Inheritance 4. Multilevel Inheritance
2. Multiple Inheritance 5. Hybrid Inheritance
3. Hierarchical Inheritance

1. Single Inheritance: - Single Inheritance is method in which a derived class has only
one base class.
#include <iostream.h>
class Value
{
protected:
int val;
public:
void set_values (int a)
{ val=a;}
In example shows a };
Base class value and a class Cube: public Value
Derived class cube {
class value contain public:
Protected member such int cube()
As val { return (val*val*val); }
Protected access };
Specifier we can use in int main ()
Derived class. {
Private member can not Cube cub;
Be Inheriting. cub.set_values (5);
cout << "The Cube of 5 is::" << cub.cube() << endl;
return 0;
}

Result:
The Cube of 5 is:: 125

2. Multiple Inheritance:- You can derive a class from any number of base classes.
Deriving a class from more than one direct base class is called multiple inheritance.

Prepared By: Dr.Vimal Vaiwala(M.Sc(I.T.), P.hD)


SDJ International College
Inheritance
Multiple inheritance enables a derived class to inherit members from more than one
parent.
Deriving directly from more than one class is usually called multiple inheritance.

Syntax:-
Class C: Public A, Public B
{
Body of D

Example
class student
{
protected:
int rno,m1,m2;
public:
void get()
{
cout<<"Enter the Roll no :";
cin>>rno;
cout<<"Enter the two marks :";
cin>>m1>>m2;
}
};
class sports
{
protected:
int sm; // sm = Sports mark
public:
void getsm()
{
cout<<"\nEnter the sports mark :";
cin>>sm;

}
};
class statement:public student,public sports
{
int tot,avg;
public:
void display()
{
tot=(m1+m2+sm);

Prepared By: Dr.Vimal Vaiwala(M.Sc(I.T.), P.hD)


SDJ International College
Inheritance
avg=tot/3;
cout<<"\n\n\tRoll No : "<<rno<<"\n\tTotal : "<<tot;
cout<<"\n\tAverage : "<<avg;
}
};
void main()
Output:
Enter the Roll no: 100
{ Enter two marks
clrscr();
statement obj; 90
obj.get(); 80
obj.getsm();
Enter the Sports Mark: 90
obj.display(); Roll No: 100
getch(); Total : 260
} Average: 86.66

Ambiguity: - In multiple inheritance the ambiguity arises when same method name is
being used by two derived class and further derivation from these two base classes.
To resolve this ambiguity we are using scope resolution operator.
class M
{ class P:public M,public N
public: {
void display() public:
{ void display(void)
cout<<"vimal \n"; {
} M::display();
}; N::display();
class N
{ }
public:
void display() };
{ int main()
cout<<"Vaiwala\n"; {
} clrscr();
}; P p;
p.display();
getch();
}
Output: Vimal
Vaiwala

3. Hierarchical Inheritance: - It is the inheritance hierarchy wherein multiple subclasses


inherit from one base class
Hierarchical Inheritance is a method of inheritance where one or more derived classes
is derived from common base class.

Prepared By: Dr.Vimal Vaiwala(M.Sc(I.T.), P.hD)


SDJ International College
Inheritance
It is the process of deriving two or more classes from single base class. And in turn
each of the derived classes can further be inherited in the same way.
The base class will include all the features that are common to the subclasses. A
subclass can be constructed by inheriting the properties of the base class. A subclass can
serve as a base class for the lower level classes and so on.
Example:- Hierarchical classification of students in a university
Student

Arts Engineering Medical


.
Syntax:- .
class A
{ Mech. Elec. Civil
-------
-------
}; class A
class B : visibility_label A { void main()
{ public: {
------- int val; int i;
------- void getvalue(int j) clrscr();
}; { B b;
class C : visibility_label A val=j; C c;
{ } cin>>i;
------- }; b.getvalue(i);
------- class B : public A b.square();
}; { c.getvalue(i);
class D : visibility_label A public: c.cube();
{ void square() getch();
------- { }
------- cout<<endl<<val*val;
}; }
}; Output
Here the visibility_label can be private, class C : public A 2
protected or public. If we do not specify {
any visibility_label then by default is public: 4
private. void cube() 8
{
cout<<endl<<val*val*val;
}
};

Prepared By: Dr.Vimal Vaiwala(M.Sc(I.T.), P.hD)


SDJ International College
Inheritance
4. Multilevel Inheritance: - The mechanism of deriving a class from another ‘derived
class’ is known as multilevel inheritance.
It is the inheritance hierarchy wherein subclass acts as a base class for other classes.
Multilevel Inheritance is a method where a derived class is derived from another
derived class.
Syntax: The class A serve as a base class for the
Base class class A{……..}; derived class B, which in turn serves as a
class B: public A{…….}; base class for the derived class C. The class
class C:public B{…….}; B is known as intermediate base class since
Intermediate it provides a link for the inheritance
Base class between A and C. The chain ABC is
known as inheritance path.
Derived
class

Example
class A class C:public B
{ {
public:
protected:
void showC()
int x;
{
public:
showA();
void showA()
showB();
{
cout<<"x*y ="<<x*y;
cout<<"enter a value for x:"<<endl;
}
cin>>x;
};
}
void main()
}; {
class B:public A C ob1;
{ ob1.showc();
protected:
}
int y;
public:
void showB() Output
{ Enter value of x = 12
cout<<"enter value for y:"; Enter value of y = 3
cin>>y; X * Y =36
}
};

5. Hybrid Inheritance The inheritance hierarchy that reflects any legal combination of
other four types of inheritance.
There could be situations where we need to apply two or more types of inheritance to
design a program.
"Hybrid Inheritance" is a method where one or more types of inheritance are combined together
and used.

Prepared By: Dr.Vimal Vaiwala(M.Sc(I.T.), P.hD)


SDJ International College
Inheritance
In figure base class A and class B and C are derived from class A.
So that path is called Hierarchical Inheritance.
Class B and C are the base class for class D. so that path is called
multiple inheritance. because there are more then one base class.

Example:-
class stu
{
protected:
int rno;
public:
void get_no(int a)
{
rno=a;
}
void put_no(void)
{
cout<<"Roll no"<<rno<<"\n";

Prepared By: Dr.Vimal Vaiwala(M.Sc(I.T.), P.hD)


SDJ International College
Inheritance
}
};
class test:public stu
{
protected:
float part1,part2;
public:
void get_mark(float x,float y)
{
part1=x;
part2=y;
}
void put_marks()
{
cout<<"Marks obtained:"<<"part1="<<part1<<"\n"<<"part2="<<part2<<"\n";
}
};
class sports
{
protected:
float score;
public:
void getscore(float s) int main()
{ {
score=s; clrscr();
} result stu;
void putscore(void) stu.get_no(123);
{ stu.get_mark(27.5,33.0);
cout<<"sports:"<<score<<"\n"; stu.getscore(6.0);
stu.display();
} return 0;
}; }
class result: public test, public sports
{
float total;
public:
void display(void); OUTPUT
};
void result::display(void) Roll no 123
{ Marks obtained : part1=27.5
total=part1+part2+score; Part2=33
put_no(); Sports=6
put_marks(); Total score = 66.5
putscore();
cout<<"Total Score="<<total<<"\n";
}

Prepared By: Dr.Vimal Vaiwala(M.Sc(I.T.), P.hD)


SDJ International College
Inheritance

Q:-2 How constructor and Destructor calls during Inheritance


A derived class inherits the members of its base class. Therefore, when a derived class
object is instantiated, its base class members must be initialized in addition to its own
members.
The base class constructor is called to initialize the base class members of the derived
class object. The base class constructor, similar to component objects in a composite
class, is called before the derived class object's constructor. Destructors are called in the
reverse order.
Example
class base {
public:
base()
{
cout << "Constructing base ... \n";
}
~base()
{
cout << "Destroying base ... \n"; }

};

class derived : public base


{
public:
derived()
{
cout << "Constructing derived... \n";
} Output
Constructing base ...
~derived()
Constructing derived...
{
Destroying derived...
cout << "Destroying derived... \n";
Destroying base ...
}
};
int main()
{
derived ob;
return 0;
}
Argument values may be passed to the base class and derived class constructors.
Member initializer lists must be used to accomplish this.
Example
class base
{
int i;
public:

Prepared By: Dr.Vimal Vaiwala(M.Sc(I.T.), P.hD)


SDJ International College
Inheritance
base(int n) : i(n)
{
cout << "Constructing base ...:\n";
cout << "i = " << i << "\n";
}
~base()
{
cout << "Destroying base ...:\n";
}
void showi()
{
cout << i << "\n";
}
};

class derived : public base {


int j;
public:
derived(int n, int m) : base(m), j(n) /* pass arg to base class
** and data member of derived */
{
cout << "Constructing derived class...:\n";
cout << "j = " << j << "\n";
}

~derived()
{
cout << "Destroying derived class...:\n";
}
void showj() Output:-
{ Constructing base...:
cout << j << "\n"; i = 20
} Constructing derived class...:
}; j = 10
int main() 20
{ 10
clrscr(); Destroying derived class...:
derived ob(10, 20); Destroying base ...:
ob.showi();
ob.showj();
getch();
return 0;
}

Q:-3 Explain Virtual Base class with example

Prepared By: Dr.Vimal Vaiwala(M.Sc(I.T.), P.hD)


SDJ International College
Inheritance
When two or more objects are derived from a common base class, we can prevent
multiple copies of the base class being present in an object derived from those objects by
declaring the base class as virtual when it is being inherited. Such a base class is known
as virtual base class. This can be achieved by preceding the base class’ name with the
word virtual.
The child has two direct base classes ‘parent 1’ and
‘parent 2’ which themselves have a common base
Grandparent class ‘grandparent’. The ‘child’ inherits the traits of
‘grandparent’ via separate paths. It can also inherit
directly as shown by the broken line. The
‘grandparent’ is sometimes referred to as indirect base
Parent 1 Parent 2 class.
Inheritance by the ‘child’ shown in fig. might pose
some problem. All the public and protected members
of ‘grandparent’ are inherited twice, first via ‘parent 1’
and again ‘parent 2’ This means ‘child’ would have
Child
duplicate sets of the members inherited from
‘grandparent’. This introduces ambiguity and should
be avoided.

Prepared By: Dr.Vimal Vaiwala(M.Sc(I.T.), P.hD)


SDJ International College
Inheritance
The duplication of inherited members due to these multiple paths can be avoided by
making the common base class (ancestor class) as virtual base class.
Syntax For example: = Assume that class sports derives the
Class A //grandparent roll_number from the class student. Then, the
{ inheritance relationship will be shown in Fig.

} Student
Class B1 : virtual public A //parent 1 As Virtual base class As Virtual base class
{

}
Class B2 : public virtual A //parent 2 Test Sports
{

}
Class C : public B1, public B2 //child
{ Result
//Only one copy of A
//will be inherited
} Virtual Base Class
Note: - The Keyword virtual and public
may be use in either order.

Example
class student
{
protected:
int roll_number;
public:
void get_number(int a)
{
roll_number =a;
}
void put_number(void)
{
out<<"Roll no"<< roll_number <<"\n";
}
};
class test: virtual public student
{
protected:
float part1,part2;
public:
void get_mark(float x,float y)
{

Prepared By: Dr.Vimal Vaiwala(M.Sc(I.T.), P.hD)


SDJ International College
Inheritance
part1=x;
part2=y;
}
void put_marks()
{
cout<<"Marks obtained:"<<"part1="<<part1<<"\n"<<"part2="<<part2<<"\n";
}
};
class sports:public virtual student
{
protected:
float score;
public:
void get_score(float s) int main()
{ {
score=s; clrscr();
} result stu;
void put_score(void) stu.get_number(123);
{ stu.get_mark(27.5,33.0);
cout<<"sports:"<<score<<"\n"; stu.get_score(6.0);
stu.display();
} return 0;
}; }
class result: public test, public sports
{
float total;
public:
void display(void); OUTPUT
};
void result::display(void) Roll no 123
{ Marks obtained : part1=27.5
total=part1+part2+score; Part2=33
put_number(); Sports=6
put_marks(); Total score = 66.5
put_score();
cout<<"Total Score="<<total<<"\n";
}
Q:-4 Explain This Pointer
C++ uses unique keyword called this to represent an object that invokes a member
function. this is a pointer that points to the object for which this function was called.
This unique pointer is automatically passed to a member function when it is called. The
pointer this acts as an implicit argument to all the member functions.
class abc
{ The Private variable ‘a’ can be used directly inside a member
int a; function, like a=123;
public: We can also use the following statement to do same job:
this a=123;
Since C++ permits the use of shorthand form a=123, we have not
Prepared By: Dr.Vimal Vaiwala(M.Sc(I.T.), P.hD)
been using pointer this explicitly so far. However, we have been
SDJ International College
implicitly using the pointer this when overloading the operators using
member function.
Inheritance
void display()
{
this->a=123;
cout<<a;
}

};
Output:=
main()
123
{
clrscr();
abc a;
a.display();
getch();
}

Q:-5 Explain pointer to derived classes.


We can use pointers not only to the base objects but also to the objects of derived
classes. Pointers to objects of a base class are type-compatible with pointers to objects of
a derived class. Therefore, single pointer variable can be made to point object belonging
to different classes.
Explanation of Example
Example In function main, we create two pointers that point to
class CPolygon objects of class CPolygon (ppoly1 and ppoly2). Then we
{ assign references to rect and trgl to these pointers, and
protected: because both are objects of classes derived from CPolygon,
int width, height; both are valid assignment operations.
public:
void set_values (int a, int b)
{
width=a; height=b;
}
};
class CRectangle: public CPolygon
{
public:
int area ()
{
return (width * height);
}
};

class CTriangle: public CPolygon


{ Output
public: 20
int area () 10

Prepared By: Dr.Vimal Vaiwala(M.Sc(I.T.), P.hD)


SDJ International College
Inheritance
{
return (width * height / 2);
}
};

int main () {
clrscr();
CRectangle rect;
CTriangle trgl;
CPolygon * ppoly1 = &rect;
CPolygon * ppoly2 = &trgl;
ppoly1->set_values (4,5);
ppoly2->set_values (4,5);
cout << rect.area() << endl;
cout << trgl.area() << endl;
return 0;
}
Q:-6 Explain Virtual Function With example
In object-oriented programming, a virtual function or virtual method is a function or
method whose behavior can be overridden within an inheriting class by a function with
the same signature.
When we use the same function name in both base and derived classes, the function in
base class is declared as virtual using keyword virtual preceding its normal declaration.
When a function is made virtual, C++ determines which function to use at run time
based by making the based on the type of object pointer to by base pointer, rather than the
type pointer. Thus, by making the base pointer to point to different objects, we can
execute different versions of the virtual function.
class Base
int main ()
{
{
public:
clrscr();
void display()
Base B;
{
Derived D;
cout<<"\n Display base";
Base *bptr;
}
cout<<"\n bptr points to base \n";
virtual void show()
bptr=&B;
{
bptr -> display();//call base version
cout<<"\n show base";
bptr -> show();//call base version
}
cout<<"\n\n bptr points to derived \n";
};
bptr=&D;
class Derived: public Base Output
bptr -> display();//calls base version
{ bptr
bptrpoints to base
-> show();//calls Derived version
public:
return 0;
void display()
}Display base
{ Show base
cout<<"\n Display Derived";
} bptr points to Derived

Prepared By: Dr.Vimal Vaiwala(M.Sc(I.T.), P.hD)


SDJ International College
Display base
Show derived
Inheritance
void show()
{
cout<<"\n show derived";
}
};

Rules for virtual function


1. The virtual function must be member of base class
2. They cannot be static members
3. They are accessed by using object pointers
4. Prototype of base class function & derived class must be same
5. Virtual function in base class must be defined even though it is not used
6. A virtual function can be friend function of another class
7. We could not have virtual constructor
8. If a virtual function is derived in base class, it need not be necessarily redefined in the
derived class
9. Pointer object of base class can point to any object of derived class but reverse is not
true
10. When a base pointer points to derived class, incrementing & decrementing it will not
make it point to the next object of derived class

Q:-7 Explain pure virtual function


A pure virtual function is a function declared in a base class that has no definition
relative to the base class. In such cases, the compiler requires each derived class to either
define the function or redeclare it as a pure virtual function
To create a pure virtual function, rather than define a body for the function, we simply
assign the function the value 0.
If you have a pure virtual, the class becomes abstract. You cannot create an object of it.
class base
{ void main()
public: {
//pure virtual function base *b; derived1 d1;
virtual void show()=0; b = &d1;
};
class derived1 : public base b->show();
{ }
public:
void show()
Output
{
cout<<"\n Derived 1"; Derived 1
} Q:-8 Explain Abstract Class
}; An abstract class is one that is not used to create objects. An abstract class is designed
only to act as a base class.
It is a design concept in program development and provides a base upon which other
classes may be built.
Allows the base class to provide only an interface for its derived classes.
Prevents anyone from creating an instance of this class.
A class is made abstract if at least one pure virtual function defined.

Prepared By: Dr.Vimal Vaiwala(M.Sc(I.T.), P.hD)


SDJ International College
Inheritance

Note: - Take above example

Prepared By: Dr.Vimal Vaiwala(M.Sc(I.T.), P.hD)


SDJ International College

You might also like