Unit 4
OPERATOR OVERLOADING, INHERITANCE AND
POLYMORPHISM
G.Mageshwari
Assistant Professor
Artificial Intelligence and Data Science
RMK College of Engineering and Technology
• Operator Overloading- Overloading Using Friend functions–
Inheritance– Types of inheritance Virtual Base Class- Abstract Class–
Constructors in Derived Classes- member class: nesting of classes.
Pointer to objects– this pointer- Pointer to derived Class- Virtual
functions– Pure Virtual Functions– Polymorphism
G.Mageshwari,Assistant Professor,Artificial Intelligence and & Data Science,RMKCET
Polymorphism
• The term "Polymorphism" is the combination of "poly" + "morphs"
which means many forms.
• That is, the same entity (function or operator) behaves differently in
different scenarios.
G.Mageshwari,Assistant Professor,Artificial Intelligence and &
Data Science,RMKCET
Types of Polymorphism
• Compile-time Polymorphism.
• Runtime Polymorphism.
We can implement polymorphism in C++ using the following ways:
1. Function overloading
2. Operator overloading
3. Virtual functions
4. Function overriding
G.Mageshwari,Assistant Professor,Artificial Intelligence and &
Data Science,RMKCET
Difference Between Compile Time and Run
Time Polymorphism
Compile Time Polymorphism Run Time Polymorphism
The function to be invoked is known at the compile The function to be invoked is known at the run time.
time.
It is also known as overloading, static binding and It is also known as overriding, Dynamic binding and
early binding. late binding.
Overloading is a compile time polymorphism where Overriding is a run time polymorphism where more
more than one method is having the same name but than one method is having the same name, number of
with the different number of parameters or the type parameters and the type of the parameters.
of the parameters.
It is achieved by function overloading and operator It is achieved by virtual functions and pointers.
overloading
It provides fast execution as it is known at the compile It provides slow execution as it is known at the run
time. time.
It is less flexible as mainly all the things execute at the It is more flexible as all the things execute at the run
compile time time
G.Mageshwari,Assistant Professor,Artificial Intelligence and &
Data Science,RMKCET
Function overloading - Compile Time Polymorphism
When there are multiple functions with the same name but different
parameters, then the functions are said to be overloaded, hence this is
known as Function Overloading.
Functions can be overloaded by changing the number of arguments
or/and changing the type of arguments.
G.Mageshwari,Assistant Professor,Artificial Intelligence and &
Data Science,RMKCET
Illustrate the concept of function overloading
#include <iostream> int main()
using namespace std; {
int sum(int num1, int num2) // Function with 2 int parameters // Call function with 2 int parameters
{ cout << "Sum of Two Integers using sum() = " << sum(5, 6) <<
return num1 + num2; endl;
} // Call function with 2 double parameters
double sum(double num1, double num2) // Function with 2 cout << "Sum of Two Double using sum() = " << sum(5.5, 6.6) <<
double parameters endl;
{ // Call function with 3 int parameters
return num1 + num2; cout << "Sum of Three Integers using sum() = " << sum(5, 6, 7) <<
} endl;
int sum(int num1, int num2, int num3) // Function with 3 int return 0;
parameters }
{ OUTPUT:
return num1 + num2 + num3; Sum of Two Integers using sum() = 11
} Sum of Two Double using sum() = 12.1
Sum of Three Integers using sum() = 18
G.Mageshwari,Assistant Professor,Artificial Intelligence and &
Data Science,RMKCET
Operator overloading - Compile Time Polymorphism
• we can overload an operator as long as we are operating on user defined types
like objects or structures.
• We cannot use operator overloading for basic types such as int, double, etc.
Operator overloading is basically function overloading, where different
operator functions have the same symbol but different operands.
• And, depending on the operands, different operator functions are executed.
• Operators that cannot be overloaded are
.
*
::
?:
G.Mageshwari,Assistant Professor,Artificial Intelligence and &
Data Science,RMKCET
Syntax : Example:
class Complex
Return_Type operator Symbol(Argument list)
{
{ ... .. ...
Function Body Public:
} // This can be done by declaring the function
Complex operator + (Complex c2)
• Return_Type is the value type to be returned to
{
another object. Complex temp;
temp.real = real + c2.real;
• operator symbol is the function where the operator
is a keyword. temp.imag = imag + c2.imag;
return temp;
• symbol is the operator to be overloaded. }
.. ...
};
G.Mageshwari,Assistant Professor,Artificial Intelligence and &
Data Science,RMKCET
Illustrate the concept of Unary Operator overloading
#include <iostream> int main()
using namespace std; {
class Count Count count1;
{ ++count1; // Call the "void operator ++()" function
private: count1.display();
int number; return 0;
public: }
Count() // Constructor to initialize count to 5
{
number = 5;
}
void operator ++() // Overload ++ when used as prefix
{
number = number + 1; OUTPUT:
} no of object Count using overloaded
void display()
operator ++ is : 6
{
cout << "No of object Count using overloaded operator ++ is :
" << number << endl;
}
};
G.Mageshwari,Assistant Professor,Artificial Intelligence and &
Data Science,RMKCET
C++ program to overload addition operator to add two complex numbers OUTPUT:
Input real and imaginary parts of a
#include <iostream> void print() complex number: 5 8
using namespace std; { Input real and imaginary parts of a
class Complex_num cout << x << " + " << y << "i" << endl;
complex number: 11 26
{ }
// declare data members (real and imaginary parts) };
int x, y; int main() Entered complex numbers:
public: { Complex number 1: 5 + 8i
// member function to take input for complex numbers Complex_num x1, y1, sum; Complex number 2: 11 + 26i
void input() // take input for two complex numbers
{ x1.input(); The addition of two complex
cout << "Input real and imaginary parts of a complex number: "; y1.input();
numbers is: 16 + 34i
cin >> x >> y; // add the complex numbers
} sum = x1 + y1;
// overload the binary '+' operator for addition // display the entered complex numbers and their sum
Complex_num operator + (Complex_num obj) cout << "\nEntered complex numbers: " << endl;
{ cout << "Complex number 1: ";
// create a new object for the result of addition x1.print();
Complex_num A; cout << "Complex number 2: ";
// perform the addition of real and imaginary parts separately y1.print();
A.x = x + obj.x; // display the result of addition
A.y = y + obj.y; cout << "\nThe addition of two complex numbers is: ";
return A; sum.print();
} return 0;
// function to display the complex number }
G.Mageshwari,Assistant Professor,Artificial Intelligence and &
Data Science,RMKCET
Overloading using friend function
• The friend function is a function that is not a member of a class but
has access to its private and protected members.
• When it comes to operator overloading, friend functions can be
particularly useful if you want to overload binary operators where the
left operand is not an object of the class.
G.Mageshwari,Assistant Professor,Artificial Intelligence and &
Data Science,RMKCET
Overloading using friend function
#include <iostream> Complex c1, c2, c3;
using namespace std; // Function to display the complex
number
// Reading data for two complex
void displayData() { numbers
class Complex {
cout << real << " + i" << img << endl; c1.readData();
private:
} c2.readData();
int real, img;
}; OUTPUT:
// Adding the two complex numbers Enter real and imaginary parts: 2
public:
// Function to read data
// Overloading the + operator using a
friend function
c3 = c1 + c2; 3
void readData() { Complex operator+(Complex C1, Complex Enter real and imaginary parts: 4
C2) { // Displaying the result
cout << "Enter real and imaginary 5
parts: "; Complex c; cout << "Addition of two complex
c.real = C1.real + C2.real;
numbers: "; Addition of two complex numbers: 6 + i8
cin >> real >> img;
c3.displayData();
} c.img = C1.img + C2.img;
return c;
return 0;
// Friend function to overload the + }
operator }
friend Complex operator+(Complex C1,
Complex C2); int main() {
G.Mageshwari,Assistant Professor,Artificial Intelligence and &
Data Science,RMKCET
Inheritance
• It allows us to create a new class (Derived Class) from an existing class
(Base Class). Derived Class object acquires all the properties and
behaviors of its Base Class object automatically.
• Inheritance is an is-a relationship. We use inheritance only if an is-a
relationship is present between the two classes. Here are some
examples:
• 1. A car is a vehicle
• 2. Orange is a fruit.
G.Mageshwari,Assistant Professor,Artificial Intelligence and &
Data Science,RMKCET
Advantage of Inheritance
• Code reusability: We can reuse the members of Base Class. So, there
is no need to define the member again. So less code is required in the
Derived Class
G.Mageshwari,Assistant Professor,Artificial Intelligence and &
Data Science,RMKCET
Type of Inheritance
1. Single inheritance
2. Multiple inheritance
3. Multilevel inheritance
4. Hierarchical inheritance
5. Hybrid inheritance
G.Mageshwari,Assistant Professor,Artificial Intelligence and &
Data Science,RMKCET
Single inheritance
• Single Inheritance is defined as the inheritance in which a derived
class is inherited from the only one base class
Syntax
class Base
{
// BODY OF THE BASE CLASS
};
class Derived : acess_specifier Base
{
// BODY OF THE DERIVED CLASS
};
G.Mageshwari,Assistant Professor,Artificial Intelligence and &
Data Science,RMKCET
Multiple inheritance
• Multiple inheritance is the process of deriving a new class that
inherits the attributes from two or more base classes.
Syntax
class A // Base class of C
{
// BODY OF THE CLASS A
};
class B // Base class of C
{
// BODY OF THE CLASS B
};
class C : acess_specifier A, access_specifier B // Derived class of A and B
{
// BODY OF CLASS C
};
G.Mageshwari,Assistant Professor,Artificial Intelligence and &
Data Science,RMKCET
Multilevel inheritance
• Multilevel inheritance is a process of deriving a class from another
derived class
Syntax
class A // Base class
{
// BODY OF CLASS A
};
class B : acess_specifier A // Derived class of A
{
// BODY OF CLASS B
};
class C : access_specifier B // Derived from derived class B
{
// BODY OF CLASS C
};
G.Mageshwari,Assistant Professor,Artificial Intelligence and &
Data Science,RMKCET
Hierarchical inheritance
• Hierarchical inheritance is defined as the process of deriving more
than one derived class from a single base class.
Syntax
class A // Base class of B,C,D
{
// BODY OF THE class A
};
class B : access_specifier A // Derived class of A
{
// BODY OF THE class B
};
class C : access_specifier A // Derived class of A
{
// BODY OF THE class C
};
class D : access_specifier A // Derived class of A
{
G.Mageshwari,Assistant// BODY OF THE
Professor,Artificial classand
Intelligence D&
Data};Science,RMKCET
Hybrid inheritance
• Hybrid inheritance is a combination of more than one type of inheritance.
Combining various types of inheritance like multiple, simple, and hierarchical
inheritance is known as hybrid inheritance. Syntax
class A
{
// BODY OF THE CLASS A
};
class B : public A
{
// BODY OF THE CLASS B
};
class C: public A
{
// BODY OF THE CLASS C
};
class D : public B, public C
{
//and
G.Mageshwari,Assistant Professor,Artificial Intelligence BODY
& OF THE CLASS D
Data Science,RMKCET };
Single inheritance - is defined as the inheritance in which a derived class is inherited from the only one base class.
#include<iostream>
using namespace std;
class Employee // Base Class
{
public: OUTPUT:
float salary = 900; Your Salary is:900
}; Your Bonus is:100
class Professor: public Employee // Derived Class
Your Total Salary is: 1000
{
public:
float bonus = 100;
void sum(){
cout << "Your Total Salary is: " << (salary + bonus);
}};
int main()
{
Professor p;// Creating an object of the derived class.
cout << "Your Salary is:" << p.salary << endl; // Gets the salary variable of Employee class.
cout << "Your Bonus is:" << p.bonus << endl; // Gets the bonus variable of the Professor class.
p.sum();
return 0;
G.Mageshwari,Assistant Professor,Artificial Intelligence and &
} Data Science,RMKCET
Multiple inheritance - is the process of deriving a new class that inherits the attributes from two or more base classes.
#include <iostream> void grossSalary(){
using namespace std; cout << "Your Total Salary is: " << (basicPay + bonus);
class Payroll // Base Class 1 }
{ };
public: int main(){
float basicPay = 900; Salary s; // Creating an object of the Salary(derived) class and calling the grossSalary() function.
}; s.grossSalary();
class Incentive // Base Class 2 return 0;
{ }
public:
float bonus = 100;
OUTPUT:
}; Your Total Salary is: 1000
class Salary: public Payroll, public Incentive // Deriving from Base Class1 and Base Class 2
{
public:
G.Mageshwari,Assistant Professor,Artificial Intelligence and &
Data Science,RMKCET
Multilevel inheritance- is a process of deriving a class from another derived class.
#include <iostream>
using namespace std;
class BaseClass
{ OUTPUT:
public:
This is an example of Multilevel Inheritance
void print()
{
cout << "This is an example of Multilevel Inheritance";
}
};
class DerivedClass1: public BaseClass
{
};
class DerivedClass2: public DerivedClass1 // Here class is derived from another derived class.
{
};
int main()
{
DerivedClass2 Obj;
Obj.print();
return 0;
}
G.Mageshwari,Assistant Professor,Artificial Intelligence and &
Data Science,RMKCET
Hierarchical inheritance- is defined as the process of deriving more than one derived class from a single base class.
#include <iostream> class Derived2 : public Base
using namespace std; {
class Base //single base class public:
{ void sum() {
public: cout << "\nSum= " << x + y;
int x, y; }
void getdata() { };
cout << "\nEnter value of x and y:\n"; cin >> x >> y; int main()
} {
}; Derived1 obj1; //object of derived class Derived1
class Derived1 : public Base Derived2 obj2; //object of derived class Derived2
{ obj1.getdata(); OUTPUT:
public: obj1.product(); Enter value of x and y:
void product() { obj2.getdata(); 10 20
cout << "\nProduct= " << x * y; obj2.sum(); Product= 200
} return 0; Enter value of x and y:
}; } 12
Sum= 3
G.Mageshwari,Assistant Professor,Artificial Intelligence and &
Data Science,RMKCET
Hybrid inheritance- is a combination of more than one type of inheritance.
#include <iostream> }
using namespace std; };
class World // Here is multiple Inheritance.
{ class India: public Continent, public Country {
public: public:
World() { India()
cout << "This is World!\n"; {
} cout << "This is India!";
}; }
// Here is Single Inheritance. };
class Continent: public World { int main()
public: {
Continent() { India myworld;
cout << "This is Continent\n"; return 0; OUTPUT:
}}; } This is World!
class Country { This is Continent
public: This is the Country
Country() { This is India!
cout << "This is the Country\n";
G.Mageshwari,Assistant Professor,Artificial Intelligence and &
Data Science,RMKCET
Modes of inheritance in C++
1.Public mode
2. Protected mode
3. Private mode
G.Mageshwari,Assistant Professor,Artificial Intelligence and &
Data Science,RMKCET
Constructors in Derived Classes
• Derived classes can call constructors from the base class.
• Constructors are not inherited but can be invoked explicitly to
initialize base members.
G.Mageshwari,Assistant Professor,Artificial Intelligence and &
Data Science,RMKCET
Constructors in Derived Classes
#include <iostream> Derived()
using namespace std; {
class Base { cout << "Derived constructor" << endl;
public: }
Base() };
{
cout << "Base constructor" << endl; int main() {
} Derived obj;
}; return 0;
class Derived : public Base }
{
OUTPUT:
public:
Base constructor
Derived constructor
G.Mageshwari,Assistant Professor,Artificial Intelligence and &
Data Science,RMKCET
Member Class and Nesting of Classes
• Nesting classes means defining one class within another. This allows logical
grouping and encapsulation of functionalities.
• Declaration of the class appear within another class.
• The scope of a nested class is valid only within the scope of the enclosing
class.
• This increases the use of encapsulation and creates more readable and
maintainable code
G.Mageshwari,Assistant Professor,Artificial Intelligence and &
Data Science,RMKCET
Member Class and Nesting of Classes
#include <iostream>
using namespace std; int main() {
class Outer { Outer::Inner obj;
public: obj.display();
class Inner { return 0;
public: }
void display()
{
cout << "Inner class" << endl;
}
};
};
G.Mageshwari,Assistant Professor,Artificial Intelligence and &
Data Science,RMKCET
Illustrate Nesting of Class
#include<iostream> void showData() OUTPUT:
The number is: 100
using namespace std; {
class EnclosingClass cout << "The number is: " << number;
{ }
public: };
//Declaring Nested Class };
class NestedClass int main()
{ {
private: // :: used to create object of nested class
int number; EnclosingClass :: NestedClass obj1;
public: obj1.setData(100);
void setData(int num1) obj1.showData();
{ return 0;
number = num1; }
}
G.Mageshwari,Assistant Professor,Artificial Intelligence and &
Data Science,RMKCET
Pointer to Objects
Pointers to objects allow indirect manipulation of objects and are essential in dynamic memory
management and polymorphism.
#include <iostream>
using namespace std;
class Demo {
public: OUTPUT:
void show() Pointer to object example
{
cout << "Pointer to object example" << endl;
}
};
int main() {
Demo obj;
Demo* ptr = &obj;
ptr->show();
return 0;
}
G.Mageshwari,Assistant Professor,Artificial Intelligence and &
Data Science,RMKCET
The 'this' Pointer
• The 'this' pointer is an implicit pointer available in member functions, pointing to the calling
object. It is used for disambiguation and chaining.
• Syntax
this
this->member_identifier
There can be 3 main usage of this keyword in C++.
❖ It can be used to pass current object as a parameter to another method.
❖ It can be used to refer current class instance variable.
❖ It can be used to declare indexers.
G.Mageshwari,Assistant Professor,Artificial Intelligence and &
Data Science,RMKCET
The 'this' Pointer
#include <iostream> #include<iostream>
using namespace std; OUTPUT:
using namespace std; class Employee 101 Sonoo 890000
{
class Demo { public: 102 Nakul 59000
int id;
public: string name;
void show() float salary;
Employee(int id,string name, float salary)
{ {
this->id = id;
cout << "Address of this object: " << this << endl; this->name = name;
this->salary = salary;
} }
}; void display()
{
int main() { cout<<id<<" "<<name<<" "<<salary<<endl;
}
Demo obj; OUTPUT: };
int main(void)
obj.show(); Address of this object: 0x7fff137d553f {
return 0; Employee e1 = Employee(101,"Sonoo",890000);
Employee e2 = Employee(102,"Nakul",59000);
} e1.display();
e2.display();
return 0;
}
G.Mageshwari,Assistant Professor,Artificial Intelligence and &
Data Science,RMKCET
Pointer to Derived Class
A pointer to a base class can point to derived class objects. It enables polymorphic behavior but needs
careful handling to avoid slicing issues.
#include <iostream> void show()
using namespace std; {
class Base { cout << "Derived class" << endl;
public: }
virtual void show() };
{ int main() {
cout << "Base class" << endl; Base* ptr = new Derived;
OUTPUT:
} ptr->show(); Derived class
}; delete ptr;
class Derived : public Base { return 0;
public: }
G.Mageshwari,Assistant Professor,Artificial Intelligence and &
Data Science,RMKCET
Virtual Functions
Virtual functions allow derived classes to override functions in the base class. They enable dynamic binding
and runtime polymorphism.
Virtual functions ensure that the correct function is called for an object, regardless of the type of reference (or
pointer) used for function call.
❖ They are mainly used to achieve Runtime polymorphism
❖ Functions are declared with a virtual keyword in base class.
❖ The resolving of function call is done at runtime.
G.Mageshwari,Assistant Professor,Artificial Intelligence and &
Data Science,RMKCET
Rules for Virtual Functions
❖ Virtual functions must be members of some class.
❖ Virtual functions cannot be static members.
❖ They are accessed through object pointers.
❖ They can be a friend of another class.
❖ A virtual function must be defined in the base class, even though it is not used.
❖ The prototypes of a virtual function of the base class and all the derived classes
must be identical. If the two functions with the same name but different
prototypes, C++ will consider them as the overloaded functions.
❖ We cannot have a virtual constructor, but we can have a virtual
destructor.
G.Mageshwari,Assistant Professor,Artificial Intelligence and &
Data Science,RMKCET
Virtual Functions
#include <iostream>
using namespace std;
class Base {
public:
virtual void show()
{
cout << "Base class" << endl;
} OUTPUT:
};
Derived class
class Derived : public Base {
public:
void show()
{
cout << "Derived class" << endl;
}
};
int main() {
Base* ptr = new Derived; Derived D;
ptr->show(); // Calls Derived's show() due to virtual function Base *ptr=&D;
return 0; ptr->show();
}
G.Mageshwari,Assistant Professor,Artificial Intelligence and &
Data Science,RMKCET
Virtual Base Class
• A virtual base class is used to prevent multiple instances of a base
class appearing when a class is derived from multiple classes that
share a common base class.
G.Mageshwari,Assistant Professor,Artificial Intelligence and &
Data Science,RMKCET
Virtual Base Class
#include <iostream>
using namespace std;
class Base {
public:
virtual void show()
{
cout << "Base class" << endl;
}
};
class Derived1 : virtual public Base {
};
class Derived2 : virtual public Base {
};
class Final : public Derived1, public Derived2
{
};
int main() {
Final obj;
obj.show(); // Calls Base class's show()
return 0;
}
OUTPUT:
Base class G.Mageshwari,Assistant Professor,Artificial Intelligence and &
Data Science,RMKCET
Pure Virtual Functions
• A pure virtual function is declared by assigning 0 in the base class.
• It makes the class abstract and mandates derived classes to provide
an implementation.
Syntax:
virtual void functionname() = 0;
G.Mageshwari,Assistant Professor,Artificial Intelligence and &
Data Science,RMKCET
Characteristics of Pure Virtual Function
A pure virtual function is a "do nothing" function. Here "do nothing" means
that it just provides the template, and derived class implements the
function.
It can be considered as an empty function means that the pure virtual
function does not have any definition relative to the base class.
Programmers need to redefine the pure virtual function in the derived class
as it has no definition in the base class.
A class having pure virtual function cannot be used to create direct objects
of its own. It means that the class is containing any pure virtual function
then we cannot create the object of that class.
This type of class is known as an abstract class.
G.Mageshwari,Assistant Professor,Artificial Intelligence and &
Data Science,RMKCET
Pure Virtual Functions
#include <iostream>
using namespace std; int main() {
class Shape { Circle c;
public: c.draw();
virtual void draw() = 0; // Pure virtual function return 0;
}; }
OUTPUT:
Drawing Circle
class Circle : public Shape {
public:
void draw()
{
cout << "Drawing Circle" << endl;
}
};
G.Mageshwari,Assistant Professor,Artificial Intelligence and &
Data Science,RMKCET
Abstract Class
• An abstract class cannot be instantiated. It contains at least one pure
virtual function. Abstract classes serve as templates for derived
classes.
Characteristics of Abstract Class
1. A class is abstract if it has at least one pure virtual function.
2. Abstract Classes cannot be instantiated, i.e. We cannot create an object of an abstract class. But pointers
and references of Abstract Class types can be created.
3. Classes that inherit the Abstract Class must implement all pure virtual functions. If they do not, those
classes will also be treated as abstract classes.
4. If we do not override the pure virtual function in derived class, then derived class also becomes abstract
class.
5. An abstract class can have constructors.
6. An abstract class in C++ can also be defined using struct keyword.
G.Mageshwari,Assistant Professor,Artificial Intelligence and &
Data Science,RMKCET
Abstract Class
#include <iostream> int main() {
using namespace std; Derived obj;
class Abstract { obj.show();
public: return 0;
virtual void show() = 0; // Pure virtual function }
};
class Derived : public Abstract { OUTPUT:
public: Implementation of abstract method
void show()
{
cout << "Implementation of abstract method" << endl;
}
};
G.Mageshwari,Assistant Professor,Artificial Intelligence and &
Data Science,RMKCET
Illustrate abstract class to find area of square and circle
#include <iostream> // Derived class
using namespace std; class Circle : public Shape
// Abstract class {
class Shape public:
{ float calculateArea()
protected: {
float dimension; return 3.14 * dimension * dimension;
public: } Output
void getDimension() }; Enter the length of the square: 10
{ int main() Area of square: 100
cin >> dimension; { Enter radius of the circle: 30
} Square square; Area of circle: 2826
// pure virtual Function Circle circle;
virtual float calculateArea() = 0; cout << "Enter the length of the square: ";
}; square.getDimension();
// Derived class cout << "Area of square: " << square.calculateArea()
class Square : public Shape << endl;
{ cout << "\nEnter radius of the circle: ";
public: circle.getDimension();
float calculateArea() cout << "Area of circle: " << circle.calculateArea() <<
{ endl;
return dimension * dimension; return 0;
} }
G.Mageshwari,Assistant Professor,Artificial Intelligence and &
}; Data Science,RMKCET
Polymorphism –Virtual function Function overriding
Precede the declaration of area() in the Shape class with the
keyword virtual.
To avoid the incorrect output is that the call of the function
area() is being set once by the compiler as the version defined in the
base class. This is called static resolution of the function call, or static
linkage - the function call is fixed before the program is executed.
This is also sometimes called early binding because the area()
function is set during the compilation of the program.
G.Mageshwari,Assistant Professor,Artificial Intelligence and &
Data Science,RMKCET
Polymorphism –Virtual function Function overriding
#include <iostream> };
using namespace std; class Triangle: public Shape
class Shape {
{ public:
protected: Triangle( int a = 0, int b = 0)
int width, height; {
public: width = a; Output
Shape( int a = 0, int b = 0) height = b;
{ }
Rectangle class area : 70
width = a; int area () Triangle class area : 25
height = b; {
} cout << "Triangle class area : " << (width * height)/2 << endl;
virtual int area() return (width * height / 2);
{ }
cout << "Parent class area :" << width * height << endl; };
return width * height; // Main function for the program
} int main() {
}; Shape *shape;
class Rectangle: public Shape Rectangle rec(10,7);
{ Triangle tri(10,5);
public: // store the address of Rectangle
Rectangle( int a = 0, int b = 0) shape = &rec;
{ // call rectangle area.
width = a; shape->area();
height = b; // store the address of Triangle
} shape = &tri;
int area () // call triangle area.
{ shape->area();
cout << "Rectangle class area : " << width * height << endl; return 0;
return (width * height); }
G.Mageshwari,Assistant Professor,Artificial Intelligence and &
} Data Science,RMKCET