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

NU-Lec 10_Virtual Functions and Polymorphism - I

Uploaded by

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

NU-Lec 10_Virtual Functions and Polymorphism - I

Uploaded by

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

Computer Programming

Lecture No. 10
Virtual Functions and Polymorphism
Objectives
• Polymorphism in C++
• Pointers to derived classes
• Introduction to virtual functions
Polymorphism
• The Greek word polymorphism means one name,
many forms.

• Static polymorphism :It can be achieved by using


overloading. It is defined at compilation time.

• Dynamic polymorphism : It can be implemented by using


inheritance. It is implemented at runtime .
Graphics Drawing Software
Graphics Drawing Software Classes
• Line
– Properties:- X-Y Coordinates, Length, Color
– Actions:- Draw Function, Change Color Function,
Get Area Function.
• Circle
– Properties:- X-Y Coordinates, Radius, Color
– Actions:- Draw Function, Change Color Function,
Get Area Function.
• Rectangle
– Properties:- X-Y Coordinates, Width, Height, Color
– Actions:- Draw Function, Change Color Function,
Get Area Function.
• Cylinder
– Properties:- X-Y Coordinates, Radius, Height, Color
– Actions:- Draw Function, Change Color Function,
Get Area Function.
• Triangle
– Properties:- X-Y Coordinates, Length, Width, Color
– Actions:- Draw Function, Change Color Function,
Get Area Function.
class Line
{
protected:
int x,y;
public:
Line(int ,int );
void draw(void);
int GetArea (void);
};
Line::Line(int a,int b)
{
x=a;
y=b;
}
void Line::draw(void)
{
cout << “\n Line Drawing code”;
}
int Line::GetArea (void)
{
cout << “\nLine Area “;
}
class Circle: public Line
{
protected:
int radius;
public:
Circle(int ,int, int );
void draw(void);
int GetArea (void);
};
Circle::Circle(int a,int b, int c) : Line (a, b)
{
radius = c;
}
void Circle::draw(void)
{
cout << “Circle drawing code”;
}
int Circle::GetArea (void)
{
cout << “Circle area code”;
}
class Rectangle: public Line
{
protected:
int Width, Height;
public:
Rectangle(int, int , int , int );
void draw(void);
int GetArea (void);
};
Rectangle::Rectangle(int a,int b, int c, int d) : Line (a, b )
{
Width = c; Height = d;
}
void Rectangle::draw(void)
{
cout << “Rectangle drawing code”;
}
int Rectangle::GetArea (void)
{
cout << “Rectangle area code”;
}
int main ( void )
{
Triangle t1 (3, 4, 5, 19 );
Circle c1 (3, 4, 5 );
Rectangle r1 ( 3, 4, 10 , 20 );
Cylinder c2 ( 3, 4, 5, 10 );

t1.draw ();
cout << “The area is “ << t1.GetArea ( );

c1.draw ();
cout << “The area is “ << c1.GetArea ();

r1.draw ();
cout << “The area is “ << r1.GetArea ();

c2.draw ();
cout << “The area is “ << c2.GetArea ();
return 0;
}
10

Implicit Derived-Class Object to Base-Class Object


Conversion (Note: this is NOT polymorphism)

• baseClassObject = derivedClassObject;
– This will work
• Remember, the derived class object has more members than the base
class object
– Extra data is not given to the base class
• derivedClassObject = baseClassObject;
– Error
• Unless an assignment operator is overloaded in the derived class, data
members exclusive to the derived class will be unassigned
• Base class has less data members than the derived class
• Some data members missing in the derived class object
11

Exploiting inheritance

• What can be done with different classes related by


inheritance?
– Any pointer of an object of a child class, can be stored in a
pointer to that parent class
• This is called polymorphism
How does polymorphism work?

• When a base class pointer is used to store one of


it’s children, any method declared in the base class
can be called.
• However, any methods that are not declared in the
base class can not be called.
• By default when a function is called using the base
class pointer, the method called will be the one
defined in the base class(not the child being
pointed at).
– This is often not what you want to have happen.
13

Polymorphism Defined

• The ability to take on different forms.


• Ability for different objects to interpret
functions differently
• Manipulate objects of various classes, and
invoke methods on an object without
knowing that object’s exact type.
14

Polymorphism

• extending inheritance
• Polymorphism means using the same syntax to do
different things depending on the context

• Polymorphism describes the ability of one operation


to be called for various objects, which, in turn, may
react differently.

• In C++ context, this means that different classes can


react differently for the same function call.
Polymorphism

• Why Is this Important?


– Allow subclasses to be treated like instances of their
superclasses

– Flexible architectures and designs


• high-level logic defined in terms of abstract interfaces
• relying on the specific implementation provided by
subclasses
• subclasses can be added without changing high-level
logic
Polymorphism

• Binding:
Refers to the process that is used to convert identifiers (such
as variable and function names) into machine language
addresses.
• Static binding or Early binding
– In most programming languages and in most cases the
variables are bound to a specific type at compile time
• Static binding
• Dynamic binding or Late binding
• The type of the variable can change at run time
• Using pointers to classes related by inheritance in C+
+
Polymorphism vs. Inheritance

• Inheritance is required in order to achieve


polymorphism (we must have class hierarchies).
– Re-using class definitions via extension and redefinition

• Polymorphism is not required in order to achieve


inheritance.
– An object of class A acts as an object of class B (an
ancestor to A).
Pointers to Derived Classes
• C++ allows base class pointers to point to derived
class objects.
• Let we have –
– class base { … };
– class derived : public base { … };
• Then we can write –
– base *p1; derived d_obj; p1 = &d_obj;
– base *p2 = new derived;

18
Pointers to Derived Classes
• With the help of pointers to derived classes, we can create
an array of base class objects, and that array can hold
objects of different derived classes
Line *p[4];
p[0] = new Triangle (3, 4, 5, 19 );
p[1] = new Circle (3, 4, 5 );
p[2] = new Rectangle ( 3, 4, 10 , 20 );
p[3] = new Cylinder ( 3, 4, 5, 10 );
for ( int loop = 0; loop < 4; loop ++ )
{ p[loop]->draw ();
cout << “The area is “ << p[loop]->GetArea ( );
}
Pointers to Derived Classes (contd.)
• Using a base class pointer (pointing to a derived
class object) we can access only those members of
the derived object that were inherited from the
base.

• This is because the base pointer has knowledge


only of the base class.

• It knows nothing about the members added by the


derived class.
Pointers to Derived Classes (contd.)
class base { int main()
public: {
void show() base b1;
{ b1.show(); // base
cout << “base\n”; derived d1;
} d1.show(); // derived
};
base *pb = &b1;
class derived : public base { pb->show(); // base
public:
void show() pb = &d1;
{
cout << “derived\n”; pb->show(); // base
}
}; return 0;
}
Pointers to Derived Classes (contd.)
• While it is allow for a base class
pointer to point to a derived object, the
reverse is not true.
– base b1;
– derived *pd = &b1; // compiler error
Introduction to Virtual Functions
• A virtual function is a member function that is
declared within a base class and redefined (called
overriding) by a derived class.

• It implements the “one interface, multiple


methods” philosophy that underlies
polymorphism.

• The keyword virtual is used to designate a


member function as virtual.
• Supports run-time polymorphism with the help of
base class pointers.
Virtual Functions
• A virtual function is a function that is declared with the
keyword virtual in a base class and then redefined by
a derived class.
• When a virtual function is invoked by a base class
pointer, the type of object being pointed at determines
which version of the function is called.
• The keyword virtual is only required in the base class,
but many programmers use it in derived classes simply
to remind themselves that the function is virtual.
• When you declare as virtual in a base class, you
indicate to the compiler that you want dynamic
binding for the function in any class that’s derived
from this base class
Introduction to Virtual Functions (contd.)
class base { int main() {
public: base b1;
virtual void show() { b1.show();
cout << “base\n”; derived d1;
} d1.show();
};
class derived : public base { base *pb = &b1;
public: pb->show();
void show() {
cout << “derived\n”; pb = &d1;
} pb->show();
}; }
Introduction to Virtual Functions (contd.)
class base { class d2 : public base {
public: public:
virtual void show() { void show() {
cout << “base\n”; cout << “derived-2\n”;
} }
}; };
class d1 : public base { int main() {
public: base *pb; d1 od1; d2 od2;
void show() { int n;
cout << “derived-1\n”; cin >> n;
} if (n % 2) pb = &od1;
}; else pb = &od2;
pb->show(); // guess what ??
}

Run-time polymorphism
Requirements for Virtual Functions

• Not every function can be declared virtual.


• Following functions cannot be virtual
– Non-member functions,
– Static member functions,
– Constructors, and
– Friend functions cannot be virtual.
Requirements for Virtual Functions

• For a function to behave virtually you must declare


and define it with the same name and parameter list in
any derived class as it has in the base class.

• If you have declared the base class function as const,


then you must declare the derived class function to be
const as well.

• The return type should also be the same


Requirements for Virtual Functions

• If you try to use different parameters for virtual


function then the virtual function mechanism will
not work.

• The function in the derived class will operate with


static binding.

• You should never declare a virtual function as


inline function
30

Reading References
Polymorphism:
• http://www.cplusplus.com/doc/tutorial/polymorphism/
• http://www.cs.bu.edu/teaching/cpp/polymorphism/intro/
Virtual Functions
• Rober Lafore Chapter 11, Page 504

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy