Lecture 10-Week10_Pure Virtual, abstract class
Lecture 10-Week10_Pure Virtual, abstract class
(CS1143)
Week 10
2
Concrete Class and Abstract Class
3
Abstract Class
4
Pure Virtual Function
5
No Instantiation of Objects for abstract class
For an object to be instantiated from a class, the class must have the
definitions of all member functions.
We cannot instantiate an object from an abstract class because it
does not have the definition of its pure virtual functions.
6
Definition of Pure Virtual Functions
The abstract class does not define its pure virtual function, but every
class that inherits from the abstract class must provide the definition
of each pure virtual function or declare it as a pure virtual to be
defined in the next lower level of the hierarchy.
If a derived class does not provide the definition of pure virtual
functions and also does not declare them as pure virtual, it also
becomes abstract. It will not give any error but it means now you
cannot create an object of this class also.
7
Interfaces
An abstract class can have both virtual and pure virtual functions.
In some cases, however, we may need to create a blueprint for
inherited classes.
We can define a class with all pure virtual functions.
This class is sometimes referred to as an interface; we cannot create
any implementation file from this class, only the interface file.
8
Example: Shape Class
9
10
Shape Class
11
Description
Note that we have no data members and only pure virtual member
functions in this program.
The reason is that we do not want objects instantiated from this
class; its purpose is only to force the derived classes to implement
the pure virtual member functions.
The two pure member functions force each derived class to have at
least two member functions to calculate the area and perimeter of
the corresponding shape.
12
Square
13
Rectangle
14
Triangle
15
Area of triangle with 3 sides
https://byjus.com/maths/area-of-triangle-with-3-sides/
16
Circle
17
Main
18