CSE1002 - M7 - 2 - Pure Virtual Function and Abstract Classes - 31!05!23
CSE1002 - M7 - 2 - Pure Virtual Function and Abstract Classes - 31!05!23
Programming
M.MANORANJITHAM
Assistant Professor
SCOPE
VIT Chennai
04/22/2024 1
Virtual Function
04/22/2024 2
Question 1
class A{ class C:public A, B{
int x; int z;
public: public:
A(int a) {x=a;} C( int a, int b, int c, int d)
};
{
/////////////////////////////////
A(a);
class B{
B(b,c);
int x,y;
z=d;}
public:
….
B(int a, int b) {x=a;y=b;}
}; };
Whether the program is wrong and how to correct it?
04/22/2024 3
Question 2
class A{ class B: public A{
int a; int b;
public: public:
void fun( ); void fun( );
}; };
Judgment: Ambiguity?
B b;
b.fun( );
04/22/2024 4
Question 2 (cont.)
class X{ class Z: public X, public Y{
public: public:
void fun1( ); void fun( );
…… ……
}; };
class Y{
public:
void fun1( ); Judgment: Ambiguity?
Z z;
…… z.fun1( );
};
04/22/2024 5
Virtual base class
04/22/2024 6
Virtual base class
Declaration:
class derivative : virtual <access> base {//….};
The reason:
If we have multi-inherits from different base
classes and these classes are derived from the same
base class, it will produce many copies of the same
base class. In this case, it will lead to the waste of
memory, and ambiguity.
04/22/2024 7
Example 1
class A{
public:
void showa() class D: public B, public C{
{cout<<"A"<<endl;}
public:
}; void
class B: public A{ showd(){cout<<"D"<<endl;}
public: };
void showb()
{cout<<"B"<<endl;} void main()
}; {
class C: public A{ D d;
public: d.showa();
void showc() }
{cout<<"C"<<endl;}
04/22/2024
}; 8
class structure: void main()
A A {
D d;
// d.showa(); error
B C
d.B::showa();
d.C::showa();
D }
04/22/2024 9
Example 2
Name
Sex Worker
Depart.
Worker Student Job
Name
person Age
Work-Stu Sex
Student
Depart.
The structure of the common derived class and the form of Spec.
the storage for the member data.
Num.
04/22/2024 10
Name
Person
Age
Sex
Departw.
Worker Student
Job
Departs
Spec
Work-Stu
Num.
04/22/2024 24
Virtual base class for example1
class A{
public: class D: public B, public C{
void showa() public:
{cout<<"A"<<endl;} void
};
class B: virtual public A{ showd(){cout<<"D"<<endl;}
public: };
void showb()
{cout<<"B"<<endl;}
}; void main()
class C: virtual public A{ {
public: D d;
void showc()
{cout<<"C"<<endl;} d.showa();
}; }
04/22/2024 25
New class structure of example1
A
B C
04/22/2024 26
Thinking 1 ?
class A{ class C: public A{
public: public:
void showa(){cout<<"A"<<endl; void showc(){cout<<"C"<<endl;}
} C(){cout<<"C"<<endl;} };
A(){cout<<"A"<<endl;}
class D: public B, public C{
};
public:
void showd(){cout<<"D"<<endl;}
class B: public A{ D(){cout<<"D"<<endl;}
public: };
void showb(){cout<<"B"<<endl; void main()
} {
D d;
B(){cout<<"B"<<endl;}
}
};
04/22/2024 27
Thinking 2?
class A{ class C:virtual public A{
public: public:
void showa(){cout<<"A"<<endl; void showc(){cout<<"C"<<endl;}
} C(){cout<<"C"<<endl;} };
A(){cout<<"A"<<endl;}
class D: public B, public C{
};
public:
void showd(){cout<<"D"<<endl;}
class B:virtual public A{ D(){cout<<"D"<<endl;} };
public:
void showb(){cout<<"B"<<endl; void main()
} {
D d;
B(){cout<<"B"<<endl;}
}
};
04/22/2024 28
Rules of assignment in inheritance
04/22/2024 29
Rules of assignment in inheritance
• In case of the following declarations:
• class B { //…} b;
• class D: public B {//….}d;
We can have the following rules:
1. The object of the base class can be assigned by the
object of derived class:
• b=d;
04/22/2024 30
2. The reference of the base class can be initialized by the
object of derived class:
• B & rb=d;
3. The pointers of the base class can be assigned by the
address of the object of derived class:
• B *pb=&d;
04/22/2024 31
Virtual functions
04/22/2024 32
Virtual functions
• Purpose of polymorphism
Can access different implementations of a function
with the same function name.
Design and implement systems that are more easily
extensible.
For example: overloaded functions, operator overloading,
etc.
04/22/2024 33
Virtual
•
functions (cont.)
For a class, if we have:
class Shape{
public:
void Draw();
//…}*ShapePtr,ShapeObject;
04/22/2024 34
Virtual functions (cont.)
• virtual functions for inherit
• Declaration:
• - Add keyword virtual before function prototype in base class
virtual type func_name(args);
• A base-class pointer or reference to a derived class object
will call the func_name function
• If a derived class does not define a virtual function it will
automatically inherited from the base class
04/22/2024 35
Role of virtual functions
04/22/2024 36
Example 1:
#include <iostream.h>
class B0
{
public:
virtual void display()
{cout<<"B0::display()"<<endl;}
};
class B1: public B0
{ public:
void display()
{ cout<<"B1::display()"<<endl; }
};
class D1: public B0
{ public:
void display()
{ cout<<"D1::display()"<<endl; }
};
04/22/2024 37
void main() Different case 1:
{ void main()
B0 b0, *p;
{
B1 b1;
D1 d1; B0 b0;
p=&b0; B1 b1;
p->display(); D1 d1;
p=&b1; b0.display();
p->display(); b1.display();
p=&d1;
p->display(); d1.display();
} }
04/22/2024 39
Important notes 1:
04/22/2024 40
Example 2:
class Employee
{
public:
Employee(const string& name, int dept)
: family_name(name), department(dept) {}
virtual void print() const;
private:
string first_name, family_name;
char middle_initial;
int department;
// ...
};
04/22/2024 41
void Employee::print() const
{
cout << family_name << "\t" << department << '\n';
// ...
}
04/22/2024 42
void Manager::print() const
{
Employee::print();
cout << "level\t" << level << '\n';
}
void main()
{
Employee e("Brown", 1234),*p;
Manager m("Jack", 123456, 2);
p=&e;
p->print();
p=&m;
p->print(); Result:
} Brown 1234
Jack 123456
level 2
04/22/2024 43
Important notes 2:
04/22/2024 44
Pure virtual functions
04/22/2024 47
Runtime Polymorphism
• Definition
– Ability to take more than one form
• An essential feature of an OO Language
• It builds upon Inheritance
• Allows run-time interpretation of object type for a given
class hierarchy
– Also Known as “Late Binding”
• Implemented in C++ using virtual functions
48
04/22/2024 48
Dynamic Binding
• Is the run-time determination of which function to call for
a particular object of a derived class based on the type of
the argument
• Declaring a member function to be virtual instructs the
compiler to generate code that guarantees dynamic
binding
49
04/22/2024 49
Whether constructors and
destructors can be virtual??
• Virtual constructors not allowed
• Because when a pointer is deleted only the of the class type is called
04/22/2024 50
Pure Virtual Function
• A pure virtual function is a function that has the notation "= 0"
in the declaration of that function.
• Simple Example of a pure virtual function in C++
• class SomeClass
{ public: virtual void pure_virtual() = 0; // a pure virtual
function // note that there is no function body
};
51
04/22/2024 51
The pure specifier
52
04/22/2024 52
Pure virtual functions and Abstract Class
• Abstract classes
• Sole purpose is to provide a base class for other classes
• No objects of an abstract base class can be instantiated
• Too generic to define real objects, i.e.
TwoDimensionalShape
• Can have pointers and references
• Concrete classes - classes that can instantiate objects
• Provide specifics to make real objects , i.e.
Square, Circle
04/22/2024 53
Pure virtual functions and Abstract
Class (cont.)
• Making abstract class
• Declare one or more virtual functions as “pure” by
initializing the function to zero
04/22/2024 54
class Shape
{
public:
virtual void rotate(int) = 0; // pure virtual functions
virtual void draw() = 0; // pure virtual functions
virtual bool is_closed() = 0; // pure virtual functions
// ...
};
};
04/22/2024 56
class D1: public B0
{
public:
void display ( ) {cout<<"D1::display ( ) "<<endl;}
};
void main()
{ B0 *p;
B1 b1; Result:
D1 d1; B1::display()
p=&b1;
p->display();
D1::display()
p=&d1;
p->display();
04/22/2024 } 57
Abstract Classes
04/22/2024 62
Abstract Classes
• A class with one or more pure virtual functions is known as
“Abstract Class”
• Objects of abstract class can’t be created
• Abstract Class is a class which contains at least one Pure
Virtual function in it.
• Abstract classes are used to provide an Interface for its sub
classes.
• Classes inheriting an Abstract Class must provide definition to
the pure virtual function, otherwise they will also become
abstract class.
• But pointer of abstract class can hold address of derived class
63
04/22/2024 63
Why we need a abstract class?
• Lets we have a class Animal, animal sleeps, animal make
sound, etc.
• For now I am considering only these two behaviors and
creating a class Animal with two functions sleeping() and
sound() .
• Now, we know that animal sounds are different dog says
“woof”, cat says “meow” .
• So what implementation do I give in Animal class for the
function or method sound()?
04/22/2024 64
Why we need a abstract class?
• So what implementation do I give in Animal
class for the function or method sound()
• only the correct way of doing this would be making this
function pure abstract
• so that we do not need give implementation in Animal
class
• but all the classes that inherits Animal class must give
implementation to this function.
• This is the way that all the Animals have sound but they
have their unique sound.
04/22/2024 65
04/22/2024 66
Simple Example
Math Symbol Problem
• Create an abstract class MathSymbol may provide a pure
virtual function doOperation(), and
67
04/22/2024 67
Algorithm for Math Symbol Problem
• Create Mathsymbol abstract class with doOperation()
pure virtual function.
• Create plus class derived from Mathsymbol.
• Create minus class dervied from Mathsymbol.
• Perform addition in plus class using doOperation()
pure virtual function.
• Perform subtraction in minus class using
doOperation() pure virtual function.
• Print each values in respective classes.
68
04/22/2024 68
Class Diagram using Dia
69
04/22/2024 69
Example
• Some classes exist logically but not physically.
• Example : Mathsymbol
– Mathsymbol M;
– Mathssymbol makes sense only as a base of some classes derived
from it. Serves as a “category”
– Hence instantiation of such a class must be prevented
class Mathsymbol //Abstract
{
public :
//Pure virtual Function
virtual void doOperation() = 0;
}
Minus m; // Valid
Plus p; // error : variable of an abstract class
71
04/22/2024 71
• It is still possible to provide definition of a pure virtual
function in the base class
• The class still remains abstract and functions must be
redefined in the derived classes, but a common piece of
code can be kept there to facilitate reuse
• In this case, they can not be declared inline
74
04/22/2024 74
Difference b/w Virtual and Pure
Virtual Function
• A pure virtual function makes the class it is
defined for abstract. Abstract classes cannot be
instantiated. Derived classes need to
override/implement all inherited pure virtual
functions. If they do not, they too will become
abstract. In C++, a class can define a pure
virtual function that has an implementation.
75
04/22/2024 75
04/22/2024 76