0% found this document useful (0 votes)
28 views57 pages

CSE1002 - M7 - 2 - Pure Virtual Function and Abstract Classes - 31!05!23

Uploaded by

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

CSE1002 - M7 - 2 - Pure Virtual Function and Abstract Classes - 31!05!23

Uploaded by

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

CSE1002 - Problem Solving and Object Oriented

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

Person Person person Age

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.

The structure of the derived class from virtual base class.

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;

• We can have two polymorphisms:


ShapePtr->Draw();
• Compiler implements dynamic binding
• Function determined during execution time
ShapeObject.Draw();
• Compiler implements static binding
• Function determined during compile-time

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

 Improve the reuse of the code.


 Provide the uniform interface of the same actions for
the sub-classes.
 Eliminate the time consuming and error prone.

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();
} }

Result1: B0::display() B1::display( ) D1::display()

Result2: B0::display() B1::display( ) D1::display()


04/22/2024 38
Different case 2:
class D1: public B0
{ };

With the original main function.

Result: B0::display() B1::display( ) B0::display()

If a derived class does not define the virtual function, it


will use the same definition of the virtual function as the
base class.

04/22/2024 39
Important notes 1:

 It cannot be a static member function.


 Add a keyword virtual before the function prototype, and
cannot be used for the definition outside the class.
 Can be inherited, all the functions with the same name in
the derived class belong to virtual function.
 Called be the pointer or reference of the base class, and
decided by the pointer to the class.

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';
// ...
}

class Manager : public Employee


{
public:
Manager(const string& name, int dept, int lvl)
: Employee(name, dept),
level(lvl)
{}
void print() const;
// ...
private:
int level;
// ...
};

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:

 Virtual functions can not be defined as friend functions .


 Virtual functions can not be overloaded, they must be
defined as the same declarations as in the base class with
or without virtual.
 Constructors can not be virtual functions, but destructors
can.

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

• But virtual destructors are allowed

• Because when a pointer is deleted only the of the class type is called

• Static binding is done

• To do dynamic binding make destructors as virtual

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

• The "= 0" portion of a pure virtual function is also known as


the pure specifier.
• Pure specifier appended to the end of the virtual function
definition may look like the function is being assigned a value
of 0, that is not true.
• The notation "= 0" is just there to indicate that the virtual
function is a pure virtual function, and that the function has no
body or definition.

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

virtual type func_name(args)= 0;


• Pure virtual function

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
// ...
};

• Shape s; // error: variable of abstract class Shape


04/22/2024 55
Example 1:
#include <iostream.h>
class B0 {
public:
virtual void display( )=0;
};

class B1: public B0


{
public:
void display ( ) {cout<<"B1::display ( ) "<<endl;}

};

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

• create two more classes Plus and Minus implement


doOperation() to provide concrete implementations of
addition in Plus class and subtraction in Minus class.

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

Mathsymbol M; // error : variable of an abstract class


70
04/22/2024 70
• A pure virtual function not defined in the derived class
remains a pure virtual function.
• Hence derived class also becomes abstract
class Plus : public Mathsymbol{ //No doOperation() - Abstract
public :
void print(){
cout << “Doing Addition” << endl;
}
class Minus : public Mathsymbol {
public :
void doOperation(){ // Override Mathsymbol:: doOperation()
int a=10,b=5;
cout << “Subtration is = ” <<a-b<< endl;
}

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

class Mathsymbol { //Abstract


public : class Minus : public Mathsymbol
virtual void doOperation() = 0;
{
};
public :
void doOperation(){
// OK, not defined inline
Mathsymbol::doOperation(); //Reuse
void Mathsymbol::doOperation(){
cout <<“Subtraction”<< endl;
cout << “Arithmetic" << endl;
}
}
72
04/22/2024 72
Example: Pure Virtual Functions
class A { • A is an abstract (base) class
public:
– Similar to an interface in Java
virtual void x() = 0;
virtual void y() = 0; – Declares pure virtual functions (=0)
}; – May also have non-virtual methods, as well as virtual
methods that are not pure virtual
class B : public A {
public: • Derived classes override pure virtual
virtual void x();
};
methods
– B overrides x(), C overrides y()
class C : public B {
public: • Can’t instantiate an abstract class
virtual void y();
– class that declares pure virtual functions
};
– or inherits ones that are not overridden
int main () { – A and B are abstract, can create a C
A * ap = new C;
ap->x (); • Can still have a pointer or reference to an
ap->y ();
delete ap; abstract class type
return 0; – Useful for polymorphism
}; 73
04/22/2024 73
Pure Virtual Functions: Summary

• Pure virtual functions are useful because they make


explicit the abstractness of a class
• Tell both the user and the compiler how it was
intended to be used
• Note : It is a good idea to keep the common code as
close as possible to the root of you hierarchy

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

You might also like