Anda di halaman 1dari 16

Inheritance

1
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
};
int main ()
Specifier we can use in
{
Derived class.
Private member can not Cube cub;
cub.set_values (5);
Be Inheriting.
cout << "The Cube of 5 is::" << cub.cube() << endl;
return 0;
}
Result:
The Cube of 5 is:: 125

Inheritance
2
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.
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;

Inheritance

public:
void display()
{
tot=(m1+m2+sm);
avg=tot/3;
cout<<"\n\n\tRoll No : "<<rno<<"\n\tTotal
cout<<"\n\tAverage : "<<avg;
}
};
void main()
{
clrscr();
statement obj;
obj.get();
obj.getsm();
obj.display();
getch();
}

: "<<tot;

Output:
Enter the Roll no: 100
Enter two marks
90
80
Enter the Sports Mark: 90
Roll No: 100
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
{
public:
void display()
{
cout<<"vimal \n";
}
};
class N
{
public:
void display()
{
cout<<"Vaiwala\n";
}
};

Output: Vimal
Vaiwala

class P:public M,public N


{
public:
void display(void)
{
M::display();
N::display();
}
};
int main()
{
clrscr();
P p;
p.display();
getch();
}

Inheritance

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.
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
Syntax:class A
{

Engineering

Medical

.
.
-------------

};
class B : visibility_label A
{
------------};
class C : visibility_label A
{
------------};
class D : visibility_label A
{
------------};
Here the visibility_label can be private,
protected or public. If we do not specify
any visibility_label then by default is
private.

Mech.

Elec.

class A
{
public:
int val;
void getvalue(int j)
{
val=j;
}
};
class B : public A
{
public:
void square()
{
cout<<endl<<val*val;
}
};
class C : public A
{
public:
void cube()
{
cout<<endl<<val*val*val;
}
};

Civil

void main()
{
int i;
clrscr();
B b;
C c;
cin>>i;
b.getvalue(i);
b.square();
c.getvalue(i);
c.cube();
getch();
}

Output
2
4
8

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.
The class A serve as a base class for the
Syntax:
Base class
derived class B, which in turn serves as a base
class A{..};
class for the derived class C. The class B is
class B: public A{.};
known as intermediate base class since it
class C:public B{.};
Intermediate
provides a link for the inheritance between A
Base class
and C. The chain ABC is known as
inheritance path.
Derived
class
Example
class C:public B
class A
{
{
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:
Output
void showB()
Enter value of x = 12
{
Enter value of y = 3
cout<<"enter value for y:";
X * Y =36
cin>>y;
}
};
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.

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)
{
out<<"Roll no"<<rno<<"\n";

};
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";
}

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:
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";
}
Output:void showj()
Constructing base...:
{
i = 20
cout << j << "\n";
Constructing derived class...:
}
j = 10
};
20
int main()
10
{
Destroying derived class...:
clrscr();
Destroying base ...:
derived ob(10, 20);
ob.showi();
ob.showj();
The child has two direct base classes parent 1 and
getch();
parent 2 which themselves have a common base
return 0;
class grandparent. The child inherits the traits of
}
grandparent via separate paths. It can also inherit
directly as shown by the broken line. The
Q:-3 Explain Virtual Base class with example grandparent is sometimes referred to as indirect base
When two or more objects are derived fromclass.
a common base class, we can prevent
multiple copies of the base class being present inInheritance
an object derived
from
thoseshown
objects
by the
child
in by
fig. might pose
declaring the base class as virtual when it is being
inherited.
Such
a
base
class
is
known
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
duplicate sets of the members inherited from
grandparent. This introduces ambiguity and should
be avoided.

as virtual base class. This can be achieved by preceding the base class name with the
word virtual.
Grandparent

Parent 1

Parent 2

Child

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
Class A //grandparent
{
}
Class B1 : virtual public A //parent 1
{

For example: = Assume that class sports derives the


roll_number from the class student. Then, the
inheritance relationship will be shown in Fig.
Student
As Virtual base class

As Virtual base class

}
Class B2 : public virtual A //parent 2
{
}
Class C : public B1, public B2 //child
{
//Only one copy of A
//will be inherited
}
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)
{

Test

Sports

Result
Virtual Base Class

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
{
function, like a=123;
int a;
We can also use the following statement to do same job:
public:
thisa=123;
Since C++ permits the use of shorthand form a=123, we have not
been using pointer this explicitly so far. However, we have been
implicitly using the pointer this when overloading the operators using
member function.

void display()
{
this->a=123;
cout<<a;
}
};
main()
{
clrscr();
abc a;
a.display();
getch();
}

Output:=
123

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
{
public:
int area ()

Output
20
10

{
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
bptr
-> display();//calls base version
Output
{
bptr
show();//calls
bptr ->
points
to base Derived version
public:
return 0;
void display()
} Display base
{
Show base
cout<<"\n Display Derived";
}
bptr points to Derived
Display base
Show derived

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
{
public:
//pure virtual function
virtual void show()=0;
};
class derived1 : public base
{
public:
void show()
{
cout<<"\n Derived 1";
}
Q:-8 Explain Abstract
};

void main()
{
base *b; derived1 d1;
b = &d1;
b->show();
}
Output
Derived 1

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.

Note: - Take above example

Anda mungkin juga menyukai