0% found this document useful (0 votes)
9 views

CPP Unit-V

Uploaded by

swaminaik729
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

CPP Unit-V

Uploaded by

swaminaik729
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 26

PTC++ Inheritance UNIT-V

UNIT-V : Inheritance
Inheritance: The process of getting variables &functions from super class to sub class. The
new classes are created from exited class.

Member a Basic/super/parent class


Member b

Member a
Member b
Member c Derived/sub/child class
Member d

Syntax:
class sub_class: access specifiers super class
{
------------------;
------------------;
};
Ex:
class cse2: public cse1
{
------------------;
------------------;
};

✓ The main objective of inheritance is code reusability.


Public inheritance:
#include<iostream>
using namespace std; Output:
class A A=50
{ X=10
public: Y=20
int x;
};
class B:public A
{
public:
int y;
void show()
{
cout<<"X="<<x<<endl;
cout<<"Y="<<y<<endl;
}
};
int main()
{
A a;
a.x=50;
cout<<"A="<<a.x<<endl;;
B b;

M.Ramesh, Dept of CSE, IIIT-Nuzividu,RGUKT Page 1


PTC++ Inheritance UNIT-V

b.x=10,b.y=20;
b.show();
}
Private inheritance:
#include<iostream>
using namespace std;
Output:
class A
X=10
{ Y=20 40
public:
int x;
};
class B:private A
{
public:
int y;
void show()
{
cout<<"X="<<x<<endl;
cout<<"Y="<<y<<endl;
}
B()
{
x=10;
y=20;
}
};
int main()
{
B b;
//b.x=30;→Error because x is private variable.
b.y=40;
b.show();
}

Protected inheritance:
#include<iostream>
using namespace std; Output:
class A X=20
Y=30
{
A=100
private:
int x; After updating….
public: X=20
int y; Y=30
protected: A=100 24
int z;
};
class B:protected A
{
public:
int a;
void get()
{

M.Ramesh, Dept of CSE, IIIT-Nuzividu,RGUKT Page 2


PTC++ Inheritance UNIT-V

//x=10;→Error because x is private variable.


y=20;
z=30;
a=100;
}
void show()
{
//cout<<"X="<<x<<endl;→Error because x is private variable.
cout<<"Y="<<y<<endl;
cout<<"Z="<<z<<endl;
cout<<"A="<<a<<endl;
}
};
int main()
{
B b;
b.get();
b.show();
b.a=24;
//b.z=30; ;→Error because z is protected variable.
cout<<"\nAfter updating..\n";
b.show();
}
Note:1) The Base class object can only access base class members.
2) Derived class object can access both base & derived class members.
3) Inheritance provides code reusability and extendibility.

Base class
Member a
Member b Base object

Sub class
Member a
Member b derived object
Member c
Member d

4) Inheritance decreases the code size and execution time and it increases the
performance of the program.
5) When an object is created for derived class memory allotted for the derived and base
class.
6) When empty class is crated without any members automatically the sixe of the class
is 1 byte.
Base class mode Sub class mode
Private derivation Protected derivation Public derivation
public private protected public
protected private protected protected
private Not inherited Not inherited Not inherited

M.Ramesh, Dept of CSE, IIIT-Nuzividu,RGUKT Page 3


PTC++ Inheritance UNIT-V

Ex:
class a class b:public a
{ {
private: public:
int x; y;
public: protected:
int y; z;
protected: };
int z; class b:private a
}; {
class b:protected a private:
{ y;
protected: z;
y; };
z;
};

Types of inheritance:

1. Single Inheritance
2. Multi Level Inheritance
3. Multiple Inheritance
4. Hierarchical Inheritance
5. Hybrid Inheritance
6. Multipath inheritance

1. Single inheritance: -
✓ It is a mechanism of derived a new class from only one base class.
✓ Here derived class is not used as a base class.

Public derivation:
#include<iostream> Output
using namespace std; Enter id&name=123 xyz
class student Enter height & weight=5.6 60
{
protected: Student details……
int id; Student id=123
char name[20]; Student name=xyz
public: Height=5.6
void getstudent() Weight=60
{
cout<<"Enter id & name=";
cin>>id>>name;
}

M.Ramesh, Dept of CSE, IIIT-Nuzividu,RGUKT Page 4


PTC++ Inheritance UNIT-V

};
class fitness:public student
{
float heig;
float weig;
public:
void getfitness()
{
cout<<"Enter height & weight=";
cin>>heig>>weig;
}
void show()
{
cout<<"Student id="<<id<<endl;
cout<<"Student name="<<name<<endl;
cout<<"Height="<<heig<<endl;
cout<<"weight="<<weig<<endl;
}
};
int main()
{
fitness f;
f.getstudent();
f.getfitness();
cout<<"\nStudent details...\n";
f.show();
}

Private derivation: -
#include<iostream> Output
using namespace std; Enter id&name=123 xyz
class student Enter height & weight=5.6 60
{
protected: Student details……
int id; Student id=123
char name[20]; Student name=xyz
}; Height=5.6
class fitness:private student Weight=60
{
float heig;
float weig;
public:
void getstudent()
{
cout<<"Enter id & name=";
cin>>id>>name;
}
void getfitness()
{
cout<<"Enter height & weight=";
cin>>heig>>weig;
}

M.Ramesh, Dept of CSE, IIIT-Nuzividu,RGUKT Page 5


PTC++ Inheritance UNIT-V

void show()
{
cout<<"student id="<<id<<endl;
cout<<"student name="<<name<<endl;
cout<<"Height="<<heig<<endl;
cout<<"weight="<<weig<<endl;
}
};
int main()
{
fitness f;
f.getstudent();
f.getfitness();
cout<<"\nStudent details...\n";
f.show();
}

2.Multi-level Inheritance:
✓ The procedure of deriving a class from derived class is known as Multi-level
inheritance.
Base class
Class A

Middle level class/inheritance class Class B Derived /base class

Derived class
Class C

Ex:
#include<iostream> Output:
using namespace std; Enter a value=10
class A Enter b&c=20 30
{ A=10
protected: B=20
int a; C=30
public: Addition of three class members=60
A()
{
cout<<"Enter a value=";
cin>>a;
}
};
class B:public A
{
protected:
int b;
};
class C:public B
{
protected:
int c;

M.Ramesh, Dept of CSE, IIIT-Nuzividu,RGUKT Page 6


PTC++ Inheritance UNIT-V

public:
C()
{
cout<<"Enter b&c values=";
cin>>b>>c;
}
void print()
{
cout<<"A="<<a;
cout<<"\nB="<<b;
cout<<"\nC="<<c;
}
void add()
{
cout<<"\nAddition of three class members="<<a+b+c;
}
};
int main()
{
C c;
c.print();
c.add();
}

3.Multiple Inheritance
✓ When a class is derived from more than one base class is known as “Multiple
Inheritance”.
✓ Here ,two or more classes are used from the derivation of a class.

Class A Class B Class C

Class D
Ex:
Output:
#include<iostream>
Enter a value=10
using namespace std;
Enter b & c values=20 30
class A
Enter d value=40
{
A=10
protected:
B=20
int a;
C=30
public:
D=40
A()
{
cout<<"Enter a value=";
cin>>a;
}
};
class B
{
protected:
int b;

M.Ramesh, Dept of CSE, IIIT-Nuzividu,RGUKT Page 7


PTC++ Inheritance UNIT-V

};
class C:public B
{
protected:
int c;
public:
C()
{
cout<<"Enter b & c values=";
cin>>b>>c;
}
};
class D:public A,C
{
protected:
int d;
public:
void gets()
{
cout<<"Enter d value=";
cin>>d;
}
void print()
{
cout<<"A="<<a;
cout<<"\nB="<<b;
cout<<"\nC="<<c;
cout<<"\nD="<<d;
}
};
int main()
{
D d1;
d1.gets();
d1.print();
}

4. Hierarchical Inheritance

✓ When a single base class used for derivation of two or more classes is known as
“Hierarchical Inheritance”.

Class A

A B C

Ex:
#include<iostream>
using namespace std;
class CSE

M.Ramesh, Dept of CSE, IIIT-Nuzividu,RGUKT Page 8


PTC++ Inheritance UNIT-V

{
public:
CSE() Output:
{ Welcome to CSE
cout<<"\nWelcome to CSE"; C++ is core subject..
} CPP-3 credits.
}; Welcome to CSE
class CPP:public CSE DS is core subject.
{ DS has 3 credit.
public: Welcome to CSE
CPP() maths is non-core subject.
{ maths has 2.5 credit
cout<<"\nC++ is core subject..";
}
void credit()
{
cout<<"\nCPP-3 credits.";
}
};
class DS:public CSE
{
public:
DS()
{
cout<<"\nDS is core subject.";
}
void credit()
{
cout<<"\nDS has 3 credit.";
}
};
class maths:public CSE
{
public:
maths()
{
cout<<"\nmaths is non-core subject.";
}
void credit()
{
cout<<"\nmaths has 2.5 credit.";
}
};
int main()
{
CPP c;
c.credit();
DS d;
d.credit();
maths m;
m.credit();
}

M.Ramesh, Dept of CSE, IIIT-Nuzividu,RGUKT Page 9


PTC++ Inheritance UNIT-V

5.Hybrid Inheritance: -
✓ It is a combination of single & multiple inheritance is known as “Hybrid inheritance”.

Class location Class player

fitness

Class game

✓ The class game is derived from two base class. That is location & fitness.
✓ The class fitness is derived from the one base class player.

Ex:
#include<iostream> Output:
using namespace std; Enter the following information…
class player name=xyz
{ gender=M
protected: age=25
char name[15]; height=5.6
char gender; weight=60
int age; city=vizag
}; pincode=431603
class fitness:public player game=cricket
{
protected: Entered Information
float height; name=xyz
float weight; gender=M
}; age=25
class location height=5.6
{ weight=60
protected: city=vizag
char city[10]; pincode=431603
char pin[7]; game=cricket
};
class game:public fitness,location
{
protected:
char game[15];
public:
void getdata()
{
cout<<"Enter following information...\n";
cout<<"name=";cin>>name;
cout<<"gender=";cin>>gender;
cout<<"age=";cin>>age;
cout<<"height=";cin>>height;
cout<<"weight=";cin>>weight;
cout<<"city=";cin>>city;
cout<<"pincode=";cin>>pin;
cout<<"game=";cin>>game;

M.Ramesh, Dept of CSE, IIIT-Nuzividu,RGUKT Page 10


PTC++ Inheritance UNIT-V

}
void show()
{
cout<<"\nEntered information...\n";
cout<<"\nname="<<name<<"\ngender="<<gender;
cout<<"\nage="<<age<<"\nheight="<<height;
cout<<"\nweight="<<weight<<"\ncity="<<city;
cout<<"\npincode="<<pin<<"\ngame="<<game;
}
};
int main()
{
game g;
g.getdata();
g.show();
}
6.Multipath Inheritance
✓ When a class is derived from two or more classes, those are derived from the same
base class. Such a type of inheritance is known as multipath inheritance.

Class A

Class B Class C

Class D
Ex:
#include<iostream>
using namespace std;
class A
{
protected:
int x;
};
class B:public A
{
protected:
int y;
};
class C:public A
{
protected:
int z;
};
class D:public B,C
{
int a;
};
int main()
{
D d;
}

M.Ramesh, Dept of CSE, IIIT-Nuzividu,RGUKT Page 11


PTC++ Inheritance UNIT-V

5.4 Virtual Base classes: -


✓ To overcome the ambiguity occurring due to multipath inheritance, the C++ provides
the keyword virtual.
✓ When classes are declared as virtual, the compiler takes essential caution to avoid the
duplication of member variables.
✓ We make class if it is a base class that has been used by more than one derived class as
their base class.
✓ We consider necessary care to be taken while declaring virtual classes.
i) A base class cannot be specified more than once in a derived class.
class CSE
{
-------
-------
};
class RGUKT:CSE,CSE → Illegal Declaration
{
------- Here CSE is specified twice ,
------- Hence it is illegal Declaration
};
ii) A base class can be indirectly passed to the derived class more than once
class RGUKT :public CSE
{
-------
-------
};
class IIIT :public CSE
{
-------
-------
};
Class AU :public RGUKT, public IIIT
{
------- //Legal Declaration
-------
};
Note: - In above case, each object of class AU will contain two sub-objects of class CSE
through classes RGUKT and IIIT

iii) The above case causes problem. To avoid duplication ,we add the keyword virtual to a
base class specifier.
Ex:-
class RGUKT : virtual public CSE
{
-------
-------
};
class IIIT : virtual public CSE
{
-------
-------
};
Class AU : public RGUKT, public IIIT
{
-------

M.Ramesh, Dept of CSE, IIIT-Nuzividu,RGUKT Page 12


PTC++ Inheritance UNIT-V

-------
};
The virtual keyword always appears before the class name CSE is now a virtual base
class.

Program: Output:
#include<iostream> Enter values of a1,a2,a3,a4=1
using namespace std; 234
class X
a1=1
{
a2=2
protected:
int a1; a3=3
}; a4=4
class Y:public virtual X
{
protected:
int a2;
};
class Z:public virtual X
{
protected:
int a3;
};
class XYZ:public Y,Z
{
int a4;
public:
void get()
{
cout<<"Enter values of a1,a2,a3,a4=";
cin>>a1>>a2>>a3>>a4;
}
void print()
{
cout<<"a1="<<a1<<"\na2="<<a2<<"\na3="<<a3<<"\na4="<<a4;
}
};
int main()
{
XYZ r;
r.get();
r.print();
return 0;
}

5.6 Object as a class member: -


✓ Properties of one class can be used in another class using inheritance or using object as
a member in another class.
✓ Declaring object as a class data member is also known as delegation.
✓ When a class has an object of another class as its member, such class is known as a
container class.
✓ In inheritance the derived class can use member of the base class, here derived class is
a kind of base class, we can also add new member to derived class.
✓ The class uses the properties of other classes through their objects .This relationship is
known as has-a relationship (or) containership.

M.Ramesh, Dept of CSE, IIIT-Nuzividu,RGUKT Page 13


PTC++ Inheritance UNIT-V

Program
#include<iostream>
using namespace std; Output:
class cse12 Welcome to cse12
{ Welcome to cse345
public: The strength of cse12=130
int count; The strength of cse345=195
cse12()
{
cout<<"Welcome to cse12\n";
count=130;
}
};
class cse345
{
public:
int count1;
cse12 c12; //Object as member of class
cse345()
{
count1=195;
cout<<"Welcome to cse345\n";
}
void show()
{
cout<<"The strength of cse12="<<c12.count;
cout<<"\nThe strength of cse345="<<count1;
}
};
int main()
{
cse345 c;
c.show();
return 0;
}

5.7 Qualifier classes & inheritance: -


✓ We know that when we declare a class within another class the inner class called as
nested class and the outer class known as Qualifier class.
✓ Here our requirement is to be getting the member of both inner class as well as outer
class.
Program
#include<iostream> Output:
using namespace std; Enter x,y&z values=1 2 3
class A x=1
{ y=2
public:
z=3
int x;
class B
{
public:
int y;
};
};
M.Ramesh, Dept of CSE, IIIT-Nuzividu,RGUKT Page 14
PTC++ Inheritance UNIT-V

class C: public A,A::B


{
public:
int z;
C()
{
cout<<"Enter x,y&z values=";
cin>>x>>y>>z;
}
void show()
{
cout<<"x="<<x<<"\ny="<<y<<"\nz="<<z;
}
};
int main()
{
C obj;
obj.show();
return 0;
}

5.8 overloading member function: -


✓ The derived class can have a similar function name as the base class member function.
An object of the derived class invokes the member function of derived class even if a
similar function present in base class.
Program:
#include<iostream>
using namespace std; Output:
class ABC In base class function.
{ In derived class function
public: In base class function
void display()
{
cout<<"In base class function.\n";
}
};
class XYZ: public ABC
{
public:
void display()
{
cout<<"In derived class function.\n";
}
};
int main()
{
XYZ x;
ABC a;
a.display();
x.display();
x.ABC::display();
return 0;
}

M.Ramesh, Dept of CSE, IIIT-Nuzividu,RGUKT Page 15


PTC++ Inheritance UNIT-V

Advantages of inheritance
✓ The most frequent use of inheritance is for deriving classes using existing classes,
which provides reusability. The existing classes remain unchanged, by reusability , the
development time of software is reduced.
✓ Th derived class extend the properties of base classes to generate more dominant
objects.
✓ The same base classes can be used by a number of derived classes in class hierarchy.
✓ When a class is derived from more than one class, all derived classes have similar
properties to those of base classes.
Disadvantages of inheritance
✓ Through object-oriented programming is frequently propagandized as an answer for
complicated projects, inappropriate use of inheritance makes programs more
complicated.
✓ Invoking member functions using object creation more compiler over heads.
✓ In class hierarchy, various data element un used, and the memory allocated to not
utilized.

5.8 Polymorphism: -
✓ It is a Greek word, poly means many and morphism means forms.
✓ If one thing existed in more than one form is known as polymorphism.
✓ There era two types of polymorphisms.

Polymorphism

Compile time Run time

Function Operator Virtual Function


overloading overloading

✓ We already discussed about function overloading and operator overloading concepts


that means compile time polymorphism.
✓ Now we will discuss about runtime polymorphism that is virtual function.
✓ Before going to virtual function, we should learn about inheritance and dynamic
binding concepts, because these concepts are prerequisites for virtual function, we
already known about inheritance. Now we will discuss about dynamic binding.
5.9 Binding in C++: -
✓ When a function call is encounter by the compiler during execution, the function call
is translated into machine language, and a sequential address is provided.
✓ Binding refers to the process that is to be used for converting functions and variables
into machine language addresses.
✓ Binding means a link between a function call and the real function that is executed hen
the function is called.
✓ The C++ supports two types bindings-
i. Static(early) binding
ii. Dynamic(late)binding
Static binding Dynamic binding
→When a compiler knows which function to →Dynamic binding means the actual function
call before execution, it is known as early invoked at run time is dependent on the
binding. addresses stored in the pointer.
→In this a link between function call and
actual function is made during program
execution.

M.Ramesh, Dept of CSE, IIIT-Nuzividu,RGUKT Page 16


PTC++ Inheritance UNIT-V

→Deciding a function call at compile time is →Deciding a function call at run time is called
called compile time or early binding. as dynamic binding.
→Static binding also called as compile time or →Dynamic binding also called as runtime or
early binding. late binding.
Ex: - →The drawback of static binding ,we
class RGUKT class AU overcome through dynamic binding.
public class RGUKT class AU
void CSE( ) void CSE( )
void CSE( ) void CSE( )
*a
. b →There we want to give preference to
address in pointer so just add virtual keyword
C
S in front of function in base class.
int main()E( r=&a;
{ ) r->CSE();
RGUKT *r;
AU a;
r=&a;
r->CSE();
return 0;
}
→here prints the function CSE() in RGUKT →Here prints the function CSE() in AU class.
class.
→When we compile the code, the compiler Example program:
instruct the CPU to jump to the different #include<iostream>
addresses when similar CSE() function calls using namespace std;
execute at various places in the program, this class RGUKT
is not an overloading function because it’s {
prototype is same and it is defined in different public:
classes. /*virtual*/ void CSE()
→When early binding is done compile does {
not care about the address pointer is holding. cout<<"Dept of CSE, RGUKT.";
r=&a;→Does not care about address }
r->CSE(); };
r is object of class RGUKT. So CSE() class AU:public RGUKT
function called in RGUKT class. {
→But we want to give preference to address public:
in pointer then we use virtual keyword in front void CSE()
of base class function, this concept is known {
as dynamic binding. cout<<"Dept of CSE, AU.";
}
};
int main()
{
RGUKT *r;
AU a;
r=&a;
r->CSE();
}
OUTPUT:
Without using virtual With using virtual
Dept of CSE, RGUKT. Dept of CSE,AU.

M.Ramesh, Dept of CSE, IIIT-Nuzividu,RGUKT Page 17


PTC++ Inheritance UNIT-V

5.10 Virtual functions: -


→ Virtual function is a member function of the base class, that should be redefined in the
derived class.
→ Derived class object will be referenced through a base class pointer.
→ Base class pointer will be used to invoke(call) derived class redefined functions during
runtime.
→ We need virtual function to invoke derived class redefined function through base class
pointer during runtime and to achieve runtime polymorphism.
→ If two functions with similar name have different arguments, the compiler consider
them different and the virtual function mechanism is dropped.
Rules for virtual function: -
i. The virtual function should not be static and must be a member of a class.
ii. The virtual function may be declared as a friend for another class, An object pointer can
access the virtual functions.
iii. A constructor cannot be declared as virtual, but a destructor declared as virtual.
iv. The virtual function should be defined in the public section of the class. It is also possible
to define the virtual function outside the class. In such a case the declaration is done
inside the class, and the definition is outside the class. The virtual keyword is used in the
declaration and not in the function declarator.
v. It is also possible to return a value from virtual functions similar to other functions.
vi. The prototype of the virtual function in the base class and derived class should be
exactly the same. Incase of mismatch, the compiler neglects the v’ function mechanism
and treats these functions as loaded functions.
vii. Arithmetic operations cannot be used with base class pointer.
viii. If a base class contains a virtual function and if the same function is not redefined in the
derived classes, In such a case, the base class function is invoked.
ix. The operator keyword used for operator overloading also supports the virtual
mechanism
Program: Function without virtual Program: Function with virtual
#include<iostream> #include<iostream>
using namespace std; using namespace std;
class B class B
{ {
public: public:
void fun() void virtual fun()
{ {
cout<<"Base class function."; cout<<"Base class function.\n";
} }
}; };
class D:public B class D:public B
{ {
public: public:
void fun() void fun()
{ {
cout<<"Derived class function."; cout<<"Derived class function.\n";
} }
}; };
int main() int main()
{ {
D d; B b;

M.Ramesh, Dept of CSE, IIIT-Nuzividu,RGUKT Page 18


PTC++ Inheritance UNIT-V

B *ptr=&d; b.fun();
ptr->fun();→calls the base function, D d;
even we assign sub class d.fun();
address. B *ptr=&d;
} ptr->fun();
Output: }
Base class function. Output:
Base class function.
Derived class function.
Derived class function.

Program for virtual function:


#include<iostream> Output:
using namespace std; b=10
class first d=20
{
int b;
public:
first()
{
b=10;
}
void virtual display()
{
cout<<"b="<<b<<endl;
}
};
class second:public first
{
int d;
public:
second()
{
d=20;
}
void display()
{
cout<<"d="<<d<<endl;
}
};
int main()
{
first f,*p;
second s;
p=&f;
p->display();
p=&s;
p->display();
}

M.Ramesh, Dept of CSE, IIIT-Nuzividu,RGUKT Page 19


PTC++ Inheritance UNIT-V

5.11 Array of Pointers: -


✓ Polymorphism refers to late or Dynamic bindings, that is, the selection of an entity is
decided as runtime.
✓ In class, functions(methods) with similar name can be defined, which performs
different tasks, and then the selection of the appropriate function is done using
dynamic binding.
✓ Dynamic binding associated with object pointer thus, address of different objects
stored in an array to invoke function dynamically.
Program: -
#include<iostream>
using namespace std; Output:
class A CSE in A.
{ CSE in B.
public: CSE in C.
void virtual CSE() CSE in D.
{
cout<<"CSE in A.\n";
}
};
class B:public A
{
public:
void CSE()
{
cout<<"CSE in B.\n";
}
};
class C:public A
{
public:
void CSE()
{
cout<<"CSE in C.\n";
}
};
class D:public A
{
public:
void CSE()
{
cout<<"CSE in D.\n";
}
};
int main()
{
A a;
B b;
C c;
D d;
A *p[]={&a,&b,&c,&d};
for(int i=0;i<4;i++)
p[i]->CSE();
}
M.Ramesh, Dept of CSE, IIIT-Nuzividu,RGUKT Page 20
PTC++ Inheritance UNIT-V

5.12 Pure Virtual Functions: -


✓ The member function of base class is rarely used for doing any operations such
functions are called do-nothing functions or dummy functions are pure virtual
functions.
✓ Pure virtual is function which is declared in a base class but there is no definition
related to this base class. Here function declared in base class without any code and it
is redefined in derived class.
✓ Any normal functions cannot be declared as a pure virtual function.
✓ After declaration of a pure virtual function in a class, the class becomes an abstract
class.
✓ Abstract classes cannot be used to declare any objects, if we any attempt to declare an
object will result in the error.
Declaration of Pure virtual function
Virtual void display()=0;

✓ Pure virtual functions always initialized with zero, It is used just instruct to the
compiler that the function is pure virtual function and it will not have a definition.
5.13 Abstract Class: -
✓ A pure virtual function declared in the base class cannot be used for any operations.
The class contain the pure virtual function cannot be used to objects such classes are
knowns as abstract classes or pure abstract classes.
✓ If we trying to create object for abstract classes compiler will generate error.
✓ The classes derived from the abstract classes are required to re-declare the pure virtual
functions.
✓ If we declare a derived class without pure virtual functions are called concrete classes.
✓ The concrete classes can be used to create objects.
Program for pure virtual functions & Abstract classes: -
#include<iostream>
using namespace std; Output:
class A Enter two values=10 20
{ Addition=30
protected:
int x,y;
public:
virtual void add()=0;
};
class B:public A
{
public:
void get()
{
cout<<"Enter two values=";
cin>>x>>y;
}
void add()
{
cout<<"Addition="<<x+y;
}
};
int main()
{
//A a;

M.Ramesh, Dept of CSE, IIIT-Nuzividu,RGUKT Page 21


PTC++ Inheritance UNIT-V

B b;
b.get();
b.add();
}
Program: pure virtual function.
#include<iostream>
using namespace std;
class first Output:
{ X=24
protected: d=7
int x;
public:
first()
{
x=24;
}
virtual void print()=0;
};
class second:public first
{
int d;
public:
second()
{
d=7;
}
void print()
{
cout<<"X="<<x<<"\nd="<<d;
}
};
int main()
{
first *p;
//p->print();
second s;
p=&s;
p->print();
}

5.14 Working of virtual function


✓ We know that binding means a link between a function call & real function that is
execute when the function is called.
✓ When a compiler knows which function to call before execution, it is known as
early binding.
✓ Dynamic binding means the actual function invoked at runtime is dependent on
the addresses stored in the pointer. In this binding, a link between function call
and actual function is made during program execution.
✓ The keyword virtual prevents the compiler from early binding, binding is
postponed until program execution.
Program:
#include <iostream>

M.Ramesh, Dept of CSE, IIIT-Nuzividu,RGUKT Page 22


PTC++ Inheritance UNIT-V

using namespace std;


class A
{
public:
void f1()
{ Output:
cout<<"In class A f1()..\n"; In class A f1()..
} In class B f2()..
virtual void f2() In class A f3()..
{ In class A f4()..
cout<<"In class A f2()..\n";
}
virtual void f3()
{
cout<<"In class A f3()..\n";
}
virtual void f4()
{
cout<<"In class A f4()..\n";
}
};
class B:public A
{
public:
void f1()
{
cout<<"In class B f1()..\n";
}
void f2()
{
cout<<"In class B f2()..\n";
}
void f4(int x)
{
cout<<"In class B f4()..\n";
}
};
int main()
{
A *p;
B obj1;
p=&obj1;
p->f1();
p->f2();
p->f3();
p->f4();
//p->f4(24);}

Note: -
✓ To perform late binding the compiler establisher VTABLE(virtual table) for every class
and it’s derived classes having virtual function. The VTABLE contains addresses of
virtual function.

M.Ramesh, Dept of CSE, IIIT-Nuzividu,RGUKT Page 23


PTC++ Inheritance UNIT-V

✓ The compiler puts the address of virtual functions in functions in the VTABLE. If no
function is redefined in derived class that is defined as virtual in the base class, the
compiler takes the address of the base class function.
✓ When an object of base class or derived class is created, a virtual pointer is inserted
into VTABLE called VPTR.
✓ When we are working with virtual function, the compiler declares one pointer
variable (virtual pointer) in base class. The compiler doesn’t declare in the derived
class. If the compiler automatically inserted a virtual pointer in derived class then two
vptr’s are available in derived class because base class members inherited into
derived class, then duplicate variables places in derived class so, the compiler
inserted a vptr in base class only.
✓ When we are declare a virtual function in class, that class size more than two bytes
compare to non-virtual function class.
Program:
#include <iostream>
using namespace std; Output:
class A Size of A=16
{ Size of B=4
private: Size of C=1
int x;
public: (If pointer integer is 4 bytes)
virtual void show()
{
cout<<"In A class..";
}
};
class B
{
private:
int y;
public:
void show()
{
cout<<"In B class..";
}
};
class C
{
public:
void show()
{
cout<<"In C class..";
}
};
int main()
{
A obj1;
B obj2;
C obj3;
cout<<"Size of A="<<sizeof(obj1);
cout<<"\nSize of B="<<sizeof(obj2);
cout<<"\nSize of C="<<sizeof(obj3);

M.Ramesh, Dept of CSE, IIIT-Nuzividu,RGUKT Page 24


PTC++ Inheritance UNIT-V

5.15 Object slicing: -


✓ When we assign a derived class to an instance of base class.

Baseclass b=derived class


obj

✓ Virtual functions permit to manipulate both base and derived class objects using
similar member functions with no modification.
✓ Virtual function can be invoked using a pointer or reference.
Program:
#include <iostream> Output:
using namespace std; using object...
class test In Base class x=7
{ In demo class y=12
int x; using reference...
public: In Base class x=7
test(int xx) In demo class y=12
{
x=xx;
}
virtual void cse()
{
cout<<"In Base class ";
cout<<"x="<<x;
}
};
class demo:public test
{
int y;
public:
demo(int xx,int yy):test(xx)
{
y=yy;
}
void cse()
{
test::cse();
cout<<"\nIn demo class ";
cout<<"y="<<y;
}
};
int main()
{
test t(24);
demo d(7,12);
test &r=d;
cout<<"using object...\n";
d.cse();

M.Ramesh, Dept of CSE, IIIT-Nuzividu,RGUKT Page 25


PTC++ Inheritance UNIT-V

cout<<"\nusing reference...\n";
r.cse();
}

5.16 Virtual Destructors: -


✓ Destructors can be declared as virtual. The constructor cannot be virtual.
✓ The virtual destructors are implemented in a similar manner to virtual functions.
✓ In constructor and destructor, picking order(hierarchy) or base and derived classes is
constructor.
✓ Destructor of derived and base classes are called when a derived class object
addressed by the base class pointer is detected. Constructor & destructor follows
LIFO.
Program:
#include <iostream> Without virtual
using namespace std;
class super Output:
{ Super class constructor..
public: Sub class constructor..
super() Super class destructor..
{
cout<<"Super class constructor..\n";
}
/*virtual*/~super()
{
cout<<"Super class destructor..\n";
}
}; With virtual
class sub:public super
{ Output:
public: Super class constructor..
sub() Sub class constructor..
{ Sub class destructor..
cout<<"Sub class constructor..\n"; Super class destructor..
}
~sub()
{
cout<<"Sub class destructor..\n";
}
};
int main()
{
super *s=new sub;
delete s;
}
Note:
→Here without virtual function the sub class destructor is not executed because sub class is
not binding with object of s. Here I need to execute sub class destructor , So to avoid this
problem, we prefix virtual keyword to base class destructor.

M.Ramesh, Dept of CSE, IIIT-Nuzividu,RGUKT Page 26

You might also like