0% found this document useful (0 votes)
4 views31 pages

OOP Module 4

Module 4 covers the concept of inheritance in C++, emphasizing code reuse through base and derived classes. It explains containership, the differences between containership and inheritance, and various modes and types of inheritance, including single, multiple, multilevel, hierarchical, and hybrid inheritance. Additionally, it discusses function overriding as a form of polymorphism in inheritance.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views31 pages

OOP Module 4

Module 4 covers the concept of inheritance in C++, emphasizing code reuse through base and derived classes. It explains containership, the differences between containership and inheritance, and various modes and types of inheritance, including single, multiple, multilevel, hierarchical, and hybrid inheritance. Additionally, it discusses function overriding as a form of polymorphism in inheritance.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 31

Module 4

Inheritance

Introduction to code reuse


C++ strongly supports the concept of reusability. The C++ classes can be reused in several
ways. Once a class has been written and tested, it can be adapted by another programmer
to suit their requirements. This is basically done by creating new classes, reusing the
properties of the existing ones. The mechanism of deriving a new class from an old one is
called inheritance. The old class is referred to as the base class and the new one is called
the derived class or subclass. A derived class includes all features of the generic base class
and then adds qualities specific to the derived class.

Containership
We can create an object of one class into another and that object will be a member of the
class. This type of relationship between classes is known
as containership or has_a relationship as one class contain the object of another class.
And the class which contains the object and members of another class in this kind of
relationship is called a container class.
The object that is part of another object is called contained object, whereas object that
contains another object as its part or attribute is called container object.

Difference between containership and inheritance Containership


When features of existing class are wanted inside your new class, but, not its interface
eg
1)computer system has a hard disk
2)car has an Engine, chassis, steering wheels.
Inheritance
When you want to force the new type to be the same type as the base class.
eg
1)computer system is an electronic device
2)Car is a vehicle

Employees can be of Different types as can be seen above. It can be a developer, an HR


manager, a sales executive, and so on. Each one of them belongs to Different problem
domain but the basic Characteristics of an employee are common to all.
Syntax for Containership:
// Class that is to be contained
class first {
.
.
};

// Container class
class second {

// creating object of first


first f;
.
.
};
Example 1:

// concept of Containership

#include <iostream>

using namespace std;

class first {

public:

void show()

cout << "Hello from first class\n";

}
};

// Container class

class second {

// creating object of first

first f;

public:

// constructor

second()

// calling function of first class

f.show();

};

int main()

// creating object of second

second s;

Output:
Hello from first class
Explanation:In the class second we have an object of class first. This is another type of
inheritance we are witnessing. This type of inheritance is known as has_a relationship as
we say that class second has an object of first class first as its member. From the object f
we call the function of class first.

Inheritance
The capability of a class to derive properties and characteristics from another class is
called Inheritance. Inheritance is one of the most important features of Object Oriented
Programming in C++.

Syntax of Inheritance in C++


class derived_class_name : access-specifier base_class_name
{
// body ....
};
where,
 class: keyword to create a new class
 derived_class_name: name of the new class, which will inherit the base class
 access-specifier: Specifies the access mode which can be either of private, public or
protected. If neither is specified, private is taken as default.
 base-class-name: name of the base class.

Example:
class ABC : private XYZ {...} // private derivation
class ABC : public XYZ {...} // public derivation
class ABC : protected XYZ {...} // protected derivation
class ABC: XYZ {...} // private derivation by default

Example
// C++ program to demonstrate how to inherit a class
#include <iostream>
using namespace std;
// Base class that is to be inherited
class Parent {
public:
// base class members
int id;
void print()
{
cout << "Base ID: " << id << endl;
}
};

// Sub class or derived publicly inheriting from Base


// Class(Parent)
class Child : public Parent {
public:
// derived class members
int idc;
void printID()
{
cout << "Child ID: " << idc << endl;
}
};

// main function
int main()
{
// creating a child class object
Child obj1;
// An object of class child has all data members and member functions of class parent
// so we try accessing the parents method and data from the child class object.
obj1.id= 7;
obj1.print();
// finally accessing the child class methods and data too
obj1.idc = 91;
obj1.printID();

return 0;
}

Output
Base ID: 7
Child ID: 91
In the above program, the ‘Child’ class is publicly inherited from the ‘Parent’ class so the
public data members of the class ‘Parent’ will also be inherited by the class ‘Child’.
Example 2: Access the Inherited Members of the Base Class in Derived Class
#include <iostream>
using namespace std;
class Base {
public:
// data member
int publicVar;

// member method
void display()
{
cout << "Value of publicVar: " << publicVar;
}
};

// Derived class
class Derived : public Base {
public:
// Function to display inherited member
void displayMember()
{
// accessing public base class member method
display();
}

// Function to modify inherited member


void modifyMember(int p)
{
// Directly modifying public member
publicVar = p;
}
};

int main()
{
// Create an object of Derived class
Derived obj;

// Display the initial values of inherited member


obj.modifyMember(10);

// Display the modified values of inherited member


obj.displayMember();

return 0;
}

Output
Value of publicVar: 10
In the above example, we have accessed the public members of the base class in the derived
class but we cannot access all the base class members directly in the derived class. It
depends on the mode of inheritance and the access specifier in the base class.

Modes of Inheritance
Mode of inheritance controls the access level of the inherited members of the base class in
the derived class. In C++, there are 3 modes of inheritance:
 Public Mode
 Protected Mode
 Private Mode

Public Inheritance Mode


If we derive a subclass from a public base class. Then the public member of the base class
will become public in the derived class and protected members of the base class will
become protected in the derived class.
Example:
class ABC : public XYZ {...} // public derivation
Protected Inheritance Mode
If we derive a subclass from a Protected base class. Then both public members and
protected members of the base class will become protected in the derived class.
Example:
class ABC : protected XYZ {...} // protected derivation
Private Inheritance Mode
If we derive a subclass from a Private base class. Then both public members and protected
members of the base class will become private in the derived class. They can only be
accessed by the member functions of the derived class.
Private mode is the default mode that is applied when we don’t specify any mode.
Example:
class ABC : private XYZ {...} // private derivation
class ABC: XYZ {...} // private derivation by default

The below table summarizes the above three modes and shows the access specifier of the
members of the base class in the subclass when derived in public, protected and private
modes:

Examples of Modes of Inheritance


Program to show different kinds of Inheritance Modes and their Member Access Levels
class A {
public:
int x;

protected:
int y;

private:
int z;
};

class B : public A {
// x is public
// y is protected
// z is not accessible from B
};

class C : protected A {
// x is protected
// y is protected
// z is not accessible from C
};

class D : private A // 'private' is default for classes


{
// x is private
// y is private
// z is not accessible from D
};

Types of Inheritance
The inheritance can be classified on the basis of the relationship between the derived class
and the base class. In C++, we have 5 types of inheritances:
1. Single inheritance
2. Multilevel inheritance
3. Multiple inheritance
4. Hierarchical inheritance
5. Hybrid inheritance

1. Single Inheritance
In single inheritance, a class is allowed to inherit from only one class. i.e. one base class is
inherited by one derived class only.
Syntax
class subclass_name : access_mode base_class
{
// body of subclass
};
Example:
class A
{
... .. ...
};
class B: public A
{
... .. ...
};
Implementation:
#include <iostream>
using namespace std;

// base class
class Vehicle {
public:
Vehicle() { cout << "This is a Vehicle\n"; }
};

// sub class derived from a single base classes


class Car : public Vehicle {
public:
Car() { cout << "This Vehicle is Car\n"; }
};

// main function
int main()
{
// Creating object of sub class will
// invoke the constructor of base classes
Car obj;
return 0;
}

Output
This is a Vehicle
This Vehicle is Car
2. Multiple Inheritance
Multiple Inheritance is a feature of C++ where a class can inherit from more than one class.
i.e one subclass is inherited from more than one base class.
Syntax
class subclass_name : access_mode base_class1, access_mode base_class2, ....
{
// body of subclass
};
Here, the number of base classes will be separated by a comma (‘, ‘) and the access mode
for every base class must be specified and can be different.
Example:

class A
{
... .. ...
};
class B
{
... .. ...
};
class C: public A, public B
{
... ... ...
};
Implementation:
// C++ program to illustrate the multiple inheritance
#include <iostream>
using namespace std;

// first base class


class Vehicle {
public:
Vehicle() { cout << "This is a Vehicle\n"; }
};

// second base class


class FourWheeler {
public:
FourWheeler() { cout << "This is a 4 Wheeler\n"; }
};

// sub class derived from two base classes


class Car : public Vehicle, public FourWheeler {
public:
Car() { cout << "This 4 Wheeler Vehical is a Car\n"; }
};

// main function
int main()
{
// Creating object of sub class will
// invoke the constructor of base classes.
Car obj;
return 0;
}

Output
This is a Vehicle
This is a 4 Wheeler
This 4 Wheeler Vehical is a Car

3. Multilevel Inheritance
In this type of inheritance, a derived class is created from another derived class and that
derived class can be derived from a base class or any other derived class. There can be any
number of levels.
Syntax
class derived_class1: access_specifier base_class
{
... .. ...
}
class derived_class2: access_specifier derived_class1
{
... .. ...
}
.....
Example:
class C
{
... .. ...
};
class B : public C
{
... .. ...
};
class A: public B
{
... ... ...
};
Implementation
// C++ program to implement Multilevel Inheritance
#include <iostream>
using namespace std;

// base class
class Vehicle {
public:
Vehicle() { cout << "This is a Vehicle\n"; }
};

// first sub_class derived from class vehicle


class fourWheeler : public Vehicle {
public:
fourWheeler() { cout << "4 Wheeler Vehicles\n"; }
};

// sub class derived from the derived base class fourWheeler


class Car : public fourWheeler {
public:
Car() { cout << "This 4 Wheeler Vehical is a Car\n"; }
};

// main function
int main()
{
// Creating object of sub class will
// invoke the constructor of base classes.
Car obj;
return 0;
}

Output
This is a Vehicle
4 Wheeler Vehicles
This 4 Wheeler Vehical is a Car

4. Hierarchical Inheritance
In this type of inheritance, more than one subclass is inherited from a single base class. i.e.
more than one derived class is created from a single base class.
Syntax
class derived_class1: access_specifier base_class
{
... .. ...
}
class derived_class2: access_specifier base_class
{
... .. ...
}
Example:

class A
{
// body of the class A.
}
class B : public A
{
// body of class B.
}
class C : public A
{
// body of class C.
}
class D : public A
{
// body of class D.
}
Implementation
// C++ program to implement Hierarchical Inheritance
#include <iostream>
using namespace std;

// base class
class Vehicle {
public:
Vehicle() { cout << "This is a Vehicle\n"; }
};

// first sub class


class Car : public Vehicle {
public:
Car() { cout << "This Vehicle is Car\n"; }
};

// second sub class


class Bus : public Vehicle {
public:
Bus() { cout << "This Vehicle is Bus\n"; }
};

// main function
int main()
{
// Creating object of sub class will
// invoke the constructor of base class.
Car obj1;
Bus obj2;
return 0;
}

Output
This is a Vehicle
This Vehicle is Car
This is a Vehicle
This Vehicle is Bus

5. Hybrid Inheritance
Hybrid Inheritance is implemented by combining more than one type of inheritance. For
example: Combining Hierarchical inheritance and Multiple Inheritance will create hybrid
inheritance in C++
There is no particular syntax of hybrid inheritance. We can just combine two of the above
inheritance types.
Example:
Below image shows one of the combinations of hierarchical and multiple inheritances:
class F
{
... .. ...
}
class G
{
... .. ...
}
class B : public F
{
... .. ...
}
class E : public F, public G
{
... .. ...
}
class A : public B {
... .. ...
}
class C : public B {
... .. ...
}
Implementation:
// C++ program to illustrate the implementation of Hybrid Inheritance
#include <iostream>
using namespace std;

// base class
class Vehicle {
public:
Vehicle() { cout << "This is a Vehicle\n"; }
};

// base class
class Fare {
public:
Fare() { cout << "Fare of Vehicle\n"; }
};

// first sub class


class Car : public Vehicle {
public:
Car() { cout << "This Vehical is a Car\n"; }
};

// second sub class


class Bus : public Vehicle, public Fare {
public:
Bus() { cout << "This Vehicle is a Bus with Fare\n"; }
};

// main function
int main()
{
// Creating object of sub class will
// invoke the constructor of base class.
Bus obj2;
return 0;
}

Output
This is a Vehicle
Fare of Vehicle
This Vehicle is a Bus with Fare
A Special Case of Hybrid Inheritance: Multipath Inheritance
In multipath inheritance, a class is derived from two base classes and these two base classes
in turn are derived from one common base class. An ambiguity can arise in this type of
inheritance in the most derived class. This problem is also called diamond problem due to
the diamond shape formed in the UML inheritance diagram.

Polymorphism in Inheritance
In Inheritance, we can redefine the base class member function in the derived class. This
type of inheritance is called Function Overriding. Generally, in other programming
languages, function overriding is runtime polymorphism but in C++, we can do it at both
runtime and complile time. For runtime polymorphism, we have to use the virtual
functions.

Example
// C++ program to demonstrate compile time function
// overriding
#include <iostream>
using namespace std;

class Parent {
public:
void Print()
{
cout << "Base Function" << endl;
}
};

class Child : public Parent {


public:
void Print()
{
cout << "Derived Function" << endl;
}
};

int main()
{
Child C;
C.Print();
return 0;
}

Output
Derived Function

Function Overriding
A function is a block of statements that together performs a specific task by taking some
input and producing a particular output. Function overriding in C++ is termed as the
redefinition of base class function in its derived class with the same signature i.e. return
type and parameters. It can be of both type: Compile Time and Runtime Polymorphism.

What is Function Overriding in C++?


Function overriding is a type of polymorphism in which we redefine the member function of
a class which it inherited from its base class. The function signature remains same but the
working of the function is altered to meet the needs of the derived class. So, when we call
the function using its name for the parent object, the parent class function is executed. But
when we call the function using the child object, the child class version will be executed.

Types of Function Overriding in C++


Unlike other languages such as Java where function overriding is strictly done at compile
time, C++ supports two types of function overriding:
 Compile Time Overriding
 Runtime Function Overriding

Compile Time Function Overriding


In compile time function overriding, the function call and the definition is binded at the
compilation of the program. Due to this, it is also called early binding or static binding.
class Parent {
access_modifier :

// overridden function
return_type name_of_the_function() {}
};

class child : public Parent {


access_modifier :

// overriding function
return_type name_of_the_function() {}
};
Example of Compile Time Function Overriding
// C++ program to demonstrate compile time function overriding

#include <iostream>
using namespace std;

class Parent {
public:
void Print()
{
cout << "Base Function" << endl;
}
};

class Child : public Parent {


public:
void Print()
{
cout << "Derived Function" << endl;
}
};

int main()
{
Child C;
C.Print();
return 0;
}
Output
Derived Function

Runtime Function Overriding using Virtual Function


Function overriding can also be performed at the runtime, which means that function call
will be binded to its definition during runtime (also known as late binding or dynamic
binding). This can be done with the help of virtual functions.
class Base {
public:
virtual func()
{
// definition
}
};

class Derived : public Base {


public:
func() override
{
// new definition
}
};

Here, override keyword tells the compiler that the given overridden function should be
declared as virtual in the parent class. It is a kind of double check as the program can
compile without errors even if the function is not virtual. But then, it will be compile time
polymorphism and we won’t get the desired behaviour of the function overriding.

Example of Runtime Function Overriding using Virtual Function


// C++ Program to illustrate how to implement runtime
// function overriding using virtual function
#include <iostream>
using namespace std;

class Base {
public:
// Declare the function as virtual to allow overriding
// in derived classes
virtual void display()
{
cout << "Display method of Base class" << endl;
}

// Virtual destructor to ensure proper cleanup of


// derived class objects
virtual ~Base() {}
};

class Derived : public Base {


public:
// Override the display method
void display() override
{
cout << "Display method of Derived class" << endl;
}
};

int main()
{
Base* Ptr;
Derived Obj;

// Point base class pointer to derived class object


Ptr = &Obj;

// Call the display function


// This will call the display method of the Derived
// class due to the virtual function mechanism
Ptr->display();

return 0;
}

Output
Display method of Derived class
Examples of Function Overriding in C++
Example 1: C++ Program to Call Overridden Function from Derived Class
// C++ program to demonstrate function overriding
// by calling the overridden function
// of a member function from the child class

#include <iostream>
using namespace std;

class Parent {
public:
void Print()
{
cout << "Base Function" << endl;
}
};

class Child : public Parent {


public:
void Print()
{
cout << "Derived Function" << endl;

// call of original function


Parent::Print();
}
};

int main()
{
Child C;
C. Print();
return 0;
}

Output
Derived Function
Base Function

Example 2: C++ Program to Call Overridden Function Using Pointer


// C++ program to access overridden function using pointer
// of Base type that points to an object of Derived class
#include <iostream>
using namespace std;

class Parent {
public:
void print()
{
cout << "Base Function" << endl;
}
};

class Child : public Parent {


public:
void print()
{
cout << "Derived Function" << endl;
}
};

int main()
{
Child C;
// pointer of Parent type that points to derived1
Parent* ptr = &C;

// call function of Base class using ptr


ptr->print();

return 0;
}

Output
Base Function
Example 3: C++ Program to Access of Overridden Function using Child Class Object
// C++ program to access overridden function
// in main() using the scope resolution operator ::

#include <iostream>
using namespace std;

class Parent {
public:
void print()
{
cout << "Base Function" << endl;
}
};

class Child : public Parent {


public:
void print()
{
cout << "Derived Function" << endl;
}
};

int main()
{
Child C;
C.print();

// access print() function of the Base class


C.Parent::print();
return 0;
}

Output
Derived Function
Base Function

Function Overloading Vs Function Overriding


Function Overloading Function Overriding

It can be both Compile Time or Runtime


It falls under Compile-Time polymorphism
Polymorphism

A function can be overloaded multiple A function cannot be overridden multiple


times as it is resolved at Compile time times as it is resolved at Run time

Can be executed without inheritance Cannot be executed without inheritance

They are in the same scope They are of different scopes.

Virtual Function

A virtual function (also known as virtual methods) is a member function that is declared
within a base class and is re-defined (overridden) by a derived class. When you refer to a
derived class object using a pointer or a reference to the base class, you can call a virtual
function for that object and execute the derived class’s version of the method.

 Virtual functions ensure that the correct function is called for an object, regardless of
the type of reference (or pointer) used for the function call.
 They are mainly used to achieve Runtime polymorphism.
 Functions are declared with a virtual keyword in a base class.
 The resolving of a function call is done at runtime.

Rules for Virtual Functions

1. Virtual functions cannot be static.


2. A virtual function can be a friend function of another class.
3. Virtual functions should be accessed using a pointer or reference of base class type to
achieve runtime polymorphism.
4. The prototype of virtual functions should be the same in the base as well as the
derived class.
5. They are always defined in the base class and overridden in a derived class. It is not
mandatory for the derived class to override (or re-define the virtual function), in that
case, the base class version of the function is used.
6. A class may have a virtual destructor but it cannot have a virtual constructor.
Compile time (early binding) VS runtime (late binding) behavior of Virtual Functions
Consider the following simple program showing the runtime behavior of virtual functions.
// C++ program to illustrate
// concept of Virtual Functions

#include <iostream>
using namespace std;

class base {
public:
virtual void print() { cout << "print base class\n"; }

void show() { cout << "show base class\n"; }


};

class derived : public base {


public:
void print() { cout << "print derived class\n"; }

void show() { cout << "show derived class\n"; }


};

int main()
{
base* bptr;
derived d;
bptr = &d;

// Virtual function, binded at runtime


bptr->print();

// Non-virtual function, binded at compile time


bptr->show();

return 0;
}

Output
print derived class
show base class
Explanation: Runtime polymorphism is achieved only through a pointer (or reference) of
the base class type. Also, a base class pointer can point to the objects of the base class as
well as to the objects of the derived class. In the above code, the base class pointer ‘bptr’
contains the address of object ‘d’ of the derived class.
Late binding (Runtime) is done in accordance with the content of the pointer (i.e. location
pointed to by pointer) and Early binding (Compile-time) is done according to the type of
pointer since the print() function is declared with the virtual keyword so it will be bound at
runtime (output is print derived class as the pointer is pointing to object of derived class)
and show() is non-virtual so it will be bound during compile time (output is show base
class as the pointer is of base type).

‘this’ pointer
In C++, ‘this’ pointers is a pointer to the current instance of a class
. It is used to access to the object’s data members within the member functions.
#include <iostream>
using namespace std;

// Class that uses this pointer


class A {
public:
int b;
A(int a) {

// Assigning a of this object to


// function argument a
this->b = a;
}
void display() {

// Accessing a of this object


cout << "Value: " << this->a;
}
};

int main() {

// Checking if this works for the object


A o(10);
o.display();

return 0;
}

Output
Value: 10
Difference between Base class and Derived class in C++
Syntax for creating Derive Class:

class BaseClass{
// members....
// member function
}

class DerivedClass : public BaseClass{


// members....
// member function
}
Difference between Base Class and Derived Class:

S.No. BASE CLASS DERIVED CLASS

1. A class from which properties are A class from which is inherited from
inherited. the base class.

2. It is also known as parent class or


superclass. It is also known as child class subclass.

3. It cannot inherit properties and methods It can inherit properties and methods
of Derived Class. of Base Class.

Syntax:
Syntax: class DerivedClass : access_specifier
class BaseClass{ BaseClass{
// members…. // members….
// member function // member function
4.
} }

Virtual base
Virtual base classes are used in virtual inheritance in a way of preventing multiple
“instances” of a given class appearing in an inheritance hierarchy when using multiple
inheritances.
Need for Virtual Base Classes: Consider the situation where we have one class A . This
class A is inherited by two other classes B and C. Both these class are inherited into
another in a new class D as shown in figure below.
As we can see from the figure that data members/function of class A are inherited twice
to class D. One through class B and second through class C. When any data / function
member of class A is accessed by an object of class D, ambiguity arises as to which
data/function member would be called? One inherited through B or the other inherited
through C. This confuses compiler and it displays error.
Example: To show the need of Virtual Base Class in C++
#include <iostream>
using namespace std;

class A {
public:
void show()
{
cout << "Hello from A \n";
}
};

class B : public A {
};
class C : public A {
};

class D : public B, public C {


};

int main()
{
D object;
object.show();
}
Compile Errors:
prog.cpp: In function 'int main()':
prog.cpp:29:9: error: request for member 'show' is ambiguous
object.show();
^
prog.cpp:8:8: note: candidates are: void A::show()
void show()
^
prog.cpp:8:8: note: void A::show()

How to resolve this issue?


To resolve this ambiguity when class A is inherited in both class B and class C, it is declared
as virtual base class by placing a keyword virtual as :
Syntax for Virtual Base Classes:
Syntax 1:
class B : virtual public A
{
};
Syntax 2:
class C : public virtual A
{
};
Note:
virtual can be written before or after the public. Now only one copy of data/function
member will be copied to class C and class B and class A becomes the virtual base class.
Virtual base classes offer a way to save space and avoid ambiguities in class hierarchies
that use multiple inheritances. When a base class is specified as a virtual base, it can act as
an indirect base more than once without duplication of its data members. A single copy of
its data members is shared by all the base classes that use virtual base.
Example 1
#include <iostream>
using namespace std;

class A {
public:
int a;
A() // constructor
{
a = 10;
}
};

class B : public virtual A {


};

class C : public virtual A {


};

class D : public B, public C {


};

int main()
{
D object; // object creation of class d
cout << "a = " << object.a << endl;

return 0;
}

Output
a = 10
Explanation :
The class A has just one data member a which is public. This class is virtually inherited in
class B and class C. Now class B and class C use the virtual base class A and no duplication
of data member a is done; Classes B and C share a single copy of the members in the
virtual base class A.
Example 2:
#include <iostream>
using namespace std;

class A {
public:
void show()
{
cout << "Hello from A \n";
}
};

class B : public virtual A {


};

class C : public virtual A {


};
class D : public B, public C {
};

int main()
{
D object;
object.show();
}

Output
Hello from A

Pure Virtual Functions and Abstract Classes


Sometimes implementation of all functions cannot be provided in a base class because we


don’t know the implementation. Such a class is called an abstract class.For example, let
Shape be a base class. We cannot provide the implementation of function draw() in Shape,
but we know every derived class must have an implementation of draw(). We cannot
create objects of abstract classes.
Abstract classes promote abstraction y hiding unnecessary implementation details and
focusing on the essential characteristics

A pure virtual function (or abstract function) in C++ is a virtual function for which we can
have an implementation, But we must override that function in the derived class,
otherwise, the derived class will also become an abstract class. A pure virtual function is
declared by assigning 0 in the declaration.
Example of Pure Virtual Functions
// An abstract class
class Test {
// Data members of class
public:
// Pure Virtual Function
virtual void show() = 0;

/* Other members */
};

Complete Example
A pure virtual function is implemented by classes that are derived from an Abstract class.
// C++ Program to illustrate the abstract class and virtual
// functions
#include <iostream>
using namespace std;
class Base {
// private member variable
int x;

public:
// pure virtual function
virtual void fun() = 0;

// getter function to access x


int getX() { return x; }
};

// This class inherits from Base and implements fun()


class Derived : public Base {
// private member variable
int y;

public:
// implementation of the pure virtual function
void fun() { cout << "fun() called"; }
};

int main(void)
{
// creating an object of Derived class
Derived d;

// calling the fun() function of Derived class


d.fun();

return 0;
}

Output
fun() called
Some Facts
1. A class is abstract if it has at least one pure virtual function.
2. We can have pointers and references of abstract class type.
3. If we do not override the pure virtual function in the derived class, then the derived
class also becomes an abstract class.
4. An abstract class can have constructors.
5. An abstract class in C++ can also be defined using struct keyword.

You might also like