SlideShare a Scribd company logo
Object-Oriented Programming
Using C++
(CAP444 – Unit 3)
Topics Covered
Polymorphism :
functions overloading,
overloading unary operators,
overloading binary operators,
virtual base classes,
abstract classes,
pointer to object,
this pointer,
pointer to derived class,
virtual function,
pure virtual function
3. Polymorphism.pptx
Polymorphism
 Functions overloading
 same function name but different parameters.
 same function name with different signature
 example of polymorphism(compile time)
 overloaded functions should be there in same class.
Area
getArea()
getArea()
Area = w × h
w = width
h = height
getArea()
Area = π × r2
 Area of Shapes using function overloading
 Area of Shapes using function overloading
Operator overloading
Operator overloading is a compile-time polymorphism in which the
operator is overloaded to provide the special meaning to the user-
defined data type.
• You can redefine built in operators except few:
• Scope resolution operator (::)
• sizeof
• member selector(.)
• member pointer selector(.*)
• ternary operator(?:)
Operators which can overload
Consider this example
class A
{
};
int main()
{
A a1,a2,a3;
a3= a1 + a2;
return 0;
}
This is not allowed, because the
addition operator “+” is
predefined to operate only on
built-in data types. But here,
“class A” is a user-defined type,
so the compiler generates an
error. This is where the concept
of “Operator overloading”
comes in.
Operator Overloading Syntax:
return_type operator operator_Symbol(parameters)
{
}
Example:
class A
{
public:
A operator +(A const &obj)
{
}
};
Operator overloading for Unary operators:
The unary operators operate on a single operand :
• The increment (++) and decrement (--) operators.
• The unary minus (-) operator.
• The logical not (!) operator.
Operator overloading for binary operators:
The binary operators operate on two operands :
+,
-,
*,
/,
%
a+b
Rules for Operator Overloading
Existing operators can only be overloaded.
The overloaded operator contains at least one operand of
the user-defined data type.
When unary operators are overloaded through a member
function take no explicit arguments, but, if they are
overloaded by a friend function, takes one argument.
When binary operators are overloaded through a member
function takes one explicit argument, and if they are
overloaded through a friend function takes two explicit
arguments.
Overloading Unary Operator (using member function):
Example 1: Overload minus (-) unary operator.
• In unary operator function, no arguments should be passed.
• It works only with one class objects.
• It is an overloading of an operator operating on a single operand.
Class:
Assume that class Distance takes two data-members i.e. feet and inches.
Overload operator –
Create an operator function for unary minus operator (having single operand of
Distance Type)
Operator function (-) will change the sign of distance Object.
Overloading Unary Operator:
Output:
class Distance {
public:
// Data Members
int feet, inch;
// Constructor to initialize the object's value
Distance(int f, int i)
{
this->feet = f;
this->inch = i;
}
// Overloading(-) operator to perform decrement
void operator-()
{
this->feet = -f;
this->inch = -i;
cout << "nFeet & Inches(Decrement):n"
cout << feet << "'" << inch;
}
};
// Main Code
int main()
{
// Declare and Initialize
// the constructor
Distance d1(8, -9);
// Use (-) unary operator by
// Single operand
-d1;
return 0;
}
Feet & Inches(Decrement):
-8'9
Overloading Unary Operator (using member function):
Example 2: Overload unary ++ Operator
(both prefix and postfix fashion)
Binary Operator Overloading (using member function):
• In binary operator overloading function, there should be one argument to be passed.
• It is overloading of an operator operating on two operands.
Example: Example of class Distance, add two distance objects using binary +
operator
class Distance {
public:
// Data Members
int feet, inch;
// No Parameter/Default Constructor
Distance()
{
this->feet = 0;
this->inch = 0;
}
// Parameterized Constructor
Distance(int f, int i)
{
this->feet = f;
this->inch = i;
}
// Overloading (+) operator to perform addition
// of two Distance objects
Distance operator+(Distance &d2)
{
// Create an object to return
Distance d3;
// Perform addition of feet and inches
d3.feet = this->feet + d2.feet;
d3.inch = this->inch + d2.inch;
// Return the resulting object
return d3;
}
};
Binary Operator Overloading (using member function):
Example Continue...
Output:
// Main Function Code
int main()
{
// Declaring and Initializing first object
Distance d1(8, 9);
// Declaring and Initializing second object
Distance d2(10, 2);
// Declaring third object
Distance d3;
// Use overloaded operator
d3 = d1 + d2;
// Display the result
cout << "nTotal Feet & Inches:n"
cout << d3.feet << "'" << d3.inch;
return 0;
}
Total Feet & Inches:
18'11
Binary Operator Overloading (using member function):
Example Continue... (Pictorial View of working of Binary Operator: )
Overloading Binary Assignment (=) Operator
• Overload the assignment operator (=) just as you can other operators and it can be used to create
an object just like the copy constructor.
class Distance {
private:
int feet, inches;
public:
// required constructors
Distance() {
this->feet = 0;
this->inches = 0;
}
Distance(int f, int i) {
this->feet = f;
this->inches = i;
}
void operator = (const Distance &D2
) {
this->feet = D2.feet;
this->inches = D2.inches;
}
// method to display distance
void displayDistance() {
cout << "F: " << feet << " I:" << inches << endl;
}
};
int main() {
Distance D1(11, 10), D2(5, 11);
cout << "First Distance : ";
D1.displayDistance();
cout << "Second Distance :";
D2.displayDistance();
// use assignment operator
D1 = D2;
cout << "First Distance :";
D1.displayDistance();
return 0;
}
Overloading Binary Operator (Using Friend Function)
• In this approach, the operator overloading function must precede
with friend keyword, and declare a function class scope.
• Keeping in mind, friend operator function takes two parameters
in a binary operator, varies one parameter in a unary operator.
• All the working and implementation would same as binary
operator function except this function will be implemented
outside of the class scope.
Overloading Binary Operator (Using Friend Function)
Example: Example using the friend function to overload binary + operator.
class Distance {
public:
// Data Members
int feet, inch;
// No Parameter Constructor
Distance()
{
this->feet = 0;
this->inch = 0;
}
// Constructor to initialize the object's value
// Parameterized Constructor
Distance(int f, int i)
{
this->feet = f;
this->inch = i;
}
// Declaring friend function using friend keyword
friend Distance operator+(Distance&, Distance&);
};
// Implementing friend function with two
parameters
Distance operator+(Distance& d1, Distance& d2)
// Call by reference
{
// Create an object to return
Distance d3;
// Perform addition of feet and inches
d3.feet = d1.feet + d2.feet;
d3.inch = d1.inch + d2.inch;
// Return the resulting object
return d3;
}
Overloading Binary Operator (Using Friend Function)
Example Continue...
Output:
// Main Program Code
int main()
{
// Declaring and Initializing first object
Distance d1(8, 9);
// Declaring and Initializing second object
Distance d2(10, 2);
// Declaring third object
Distance d3;
// Use overloaded operator
d3 = d1 + d2;
// Display the result
cout << "nTotal Feet & Inches:n "
cout << d3.feet << "'" << d3.inch;
return 0;
}
Total Feet & Inches:
18'11
Operators that cannot be overloaded using Friend Function
Following are the operators for which overloading is not possible in C++
using friend function:
1. function call operator ()
2. assignment operator =
3. class member access operator ->
4. subscripting operator [ ]
If these operators are overloaded using friend function, then program
will result with compilation error. These operators can be overloaded if
they are part of member functions.
NOTE: A friend function is a non-member function of the class to which it has been defined as
friend. Therefore, it just uses the functionality (functions and data) of the class. So, it does not
consist the implementation for that class. That's why it cannot be used to overload certain
class specific operators as listed above.
Virtual Base class Introduce
Virtual Base Class
• Virtual base classes are used in virtual inheritance
in a way of preventing multiple “instances” of a
given class appearing in an inheritance hierarchy
when using multiple inheritances.
Need for Virtual Base Classes:
Consider the situation where we have one class A.
This class is A is inherited by two other
classes B and C. Both these class are inherited into
another in a new class D as shown in figure below.
Student
Exam Project
Result
regNo, Name
studentDetails()
regNo, Name
studentDetails()
regNo, Name
studentDetails()
regNo, Name
studentDetails()
ambiguity arises as to which
data/function member would
be called?
Situation
Virtual Base Class
How to resolve this issue?
• To resolve this ambiguity when class A is inherited in
both class B and class C, it is declared as virtual base
class by placing a keyword virtual.
• Virtual base classes offer a way to save space and
avoid ambiguities in class hierarchies that use multiple
inheritances.
• Note: virtual can be written before or after the public.
Now only one copy of data/function member will be
copied to class C and class B and class A becomes the
virtual base class.
Virtual Base Class : An Example
Without
Virtual,
ambiguity
leads to a
Compiler Error
With Virtual
Base Class A,
No ambiguity,
Program runs
fine!
• Function Overriding (Run-time
Polymorphism)
• Virtual Function Introduce
Function Overriding – Run-time Polymorphism
• It is the redefinition of base class function in its derived class with same
signature i.e., return type and parameters are exactly the same in both base
and derived classes.
• Suppose, the same function is defined in both the derived class and the based
class. Now if we call this function using the object of the derived class, the
function of the derived class is executed.
This is known as function overriding in C++. The function in derived class
overrides the function in base class.
Function Overriding – Example
Function Overriding : Call Overridden Function Using Pointer
#include <iostream>
using namespace std;
class Base {
public:
void print() {
cout << "Base Function" << endl;
}
};
class Derived : public Base {
public:
void print() {
cout << "Derived Function" << endl;
}
};
int main() {
Derived derived1;
// pointer of Base type that points to derived1
Base* ptr = &derived1;
// call function of Base class using ptr
ptr->print();
return 0;
}
Function Overriding : Call Overridden Function Using Pointer
• In last program, we have created a pointer of Base type named ptr. This pointer points
to the Derived object derived1
• When we call the print() function using ptr, it calls the overridden function from Base.
• This is because even though ptr points to a Derived object, it is actually of Base type.
So, it calls the member function of Base.
• In order to override the Base function instead of accessing it, we need to use virtual
functions in the Base class.
Problems in method overriding : Need of Virtual Function
• Overriding using base class pointer compiler don’t know about pointer which
address is pointing because address will be decided at run time when memory
will be allocated.
• To over come this problem, we use virtual function.
• With the help of virtual function, we can override function at run time
Virtual Function in C++
• A virtual function is a member function which is declared within a base class and is
re-defined (overridden) by a derived class. When you refer to a derived class object
using a pointer or a reference to the base class, you can call a virtual function for
that object and execute the derived class’s version of the function.
 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.
Rules for Virtual Functions
• Virtual functions should be accessed using pointer or reference of base
class type to achieve runtime polymorphism.
• The prototype of virtual functions should be the same in the base as well as
derived class.
• They are always defined in the base class and overridden in a derived class.
It is not mandatory for the derived class to override (or re-define the virtual
function), in that case, the base class version of the function is used.
Virtual Function : Example
#include<iostream>
using namespace std;
class base {
public:
virtual void print()
{
cout << "print base classn";
}
void show()
{
cout << "show base classn";
}
};
class derived : public base {
public:
void print()
{
cout << "print derived classn";
}
void show()
{
cout << "show derived classn";
}
};
int main()
{
base *bptr;
derived d;
bptr = &d;
// Virtual function, binded at runtime
bptr->print();
// Non-virtual function, binded at compile time
bptr->show();
return 0;
}
Pure Virtual Function in C++
• Sometimes implementation of all function cannot be provided in a base
class because we don’t know the implementation.
• For example, let Shape be a base class. We cannot provide implementation
of function draw() in Shape, but we know every derived class must have
implementation of draw().
• A pure virtual function (or abstract function) in C++ is a virtual function for
which we don’t have an implementation in base class, we only declare it. A
pure virtual function is declared by assigning 0 in the declaration.
• We generally override a pure virtual function of base class into its derived
class to provide an implementation.
Pure Virtual Function : Example 1
int main()
{
Derived d;
d.fun();
return 0;
}
#include<iostream>
using namespace std;
class Base
{
int x;
public:
virtual void fun() = 0;
int getX() {
x =10;
return x; }
};
// This class inherits from Base and implements fun()
class Derived: public Base
{
int y;
public:
void fun() { cout << “Value of x = ” << getX(); }
};
Output:
Value of x = 10
Pure Virtual Function : Example 2
class Shape {
protected:
float dimension;
public:
void getDimension() {
cin >> dimension;
}
// pure virtual Function
virtual float calculateArea() = 0;
};
// Derived class
class Square : public Shape {
public:
float calculateArea() {
return dimension * dimension;
}
};
// Derived class
class Circle : public Shape {
public:
float calculateArea() {
return 3.14 * dimension * dimension;
}
};
int main() {
Square square;
Circle circle;
cout << "Enter the length of the square: ";
square.getDimension();
cout << "Area of square: " << square.calculateArea() << endl;
cout << "nEnter radius of the circle: ";
circle.getDimension();
cout << "Area of circle: " << circle.calculateArea() << endl;
return 0;
}
Virtual Function Vs Pure Virtual Function
Virtual Function Vs Pure Virtual Function
Abstract Class and Pure Virtual function
Abstract Class in C++
• In C++, A class is abstract if it has at least one pure virtual function.
// An abstract class
class Test
{
// Data members of class
public:
// Pure Virtual Function
virtual void show() = 0;
/* Other members */
};
In the above example, Test is an abstract class because it has a pure virtual function
show().
Abstract Class in C++
• An abstract class cannot be instantiated – meaning that we cannot create
objects of abstract class.
// pure virtual functions make
a class abstract
class Test
{
int x;
public:
virtual void show() = 0;
int getX() { return x; }
};
int main()
{
Test t;
return 0;
}
Abstract Class in C++
• Although we cannot have object of abstract class, but we can have pointers
and references of abstract class type.
class Base
{
public:
virtual void show() = 0;
};
class Derived: public Base
{
public:
void show() { cout << "In Derived n"; }
};
int main(void)
{
Base *bp = new Derived();
bp->show();
return 0;
}
Abstract Class in C++
• If we do not override pure virtual function of base class in its derived class,
then derived class also becomes abstract class.
-- Since Base has a pure virtual
function show(), so it is an abstract
class.
-- We did not override pure virtual
function show() into Derived
class, so it is also abstract class.
-- Clearly, both Base and Derived are
abstract classes here.
#include<iostream>
using namespace std;
class Base
{
public:
virtual void show() = 0;
};
class Derived : public Base {
// Empty Derived class
};
int main()
{
Derived d;
return 0;
}
Summary of Important Points about Abstract Class
1. A class is abstract if it has at least one pure virtual
function.
2. If we do not override the pure virtual function in derived class, then
derived class also becomes abstract class.
3. We cannot create objects of abstract classes.
4. We can create pointers and references of abstract class type.
5. An abstract class can have constructors.
What will be the output of the following C++ code?
#include<iostream>
using namespace std;
class Mobile
{
long int contactno;
public:
virtual void getStatus() = 0;
Mobile()
{
contactno=9898989890;
cout<<contactno;
}
};
class Person: public Mobile
{
public:
void getDetails() { cout << “Blocked”; }
};
int main()
{
Person p;
p.getDetails();
return 0;
}
MCQ
A. 9898989890
B. Blocked
C.9898989890 Blocked
D. Error
What will be the output of the following C++ code?
#include<iostream>
using namespace std;
class Mobile
{
long int contactno;
public:
virtual void getStatus() = 0;
Mobile()
{
contactno=9898989890;
cout<<contactno;
}
};
class Person: public Mobile
{
public:
void getStatus(){ cout <<“ Blocked”; }
void getDetails() { cout << “ Welcome”;
}
};
int main()
{
Person p;
p.getDetails();
return 0;
}
MCQ
A. 9898989890 Welcome
B. Blocked
C.9898989890 Blocked
D. Error
Pointer to object
• A variable that holds an address value is called a pointer variable.
• Just like other pointers, the object pointers are declared by placing in front of a object
pointer's name.
• Object can also have an address , so there is also a pointer that can point to the address of
an object. That is known as pointer to an object.
• It takes the following general form : class-name ∗ object-pointer ;
Example : class Date
{
};
Date d1;
Date *d2;
d2=&d1;
d2->functions()
object pointer
Pointer to object : An Example
#include <iostream>
using namespace std;
class Box {
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
public:
// Constructor definition
Box(double l = 2.0, double b = 2.0, double h =
2.0)
{
cout <<"Constructor called." << endl;
length = l; breadth = b; height = h;
}
double Volume()
{
return length * breadth * height;
}
};
int main()
{
Box Box1(3.3, 1.2, 1.5); // Declare box1 object
Box *ptrBox; // Declare pointer to a class.
// Save the address of first object
ptrBox = &Box1;
// Now try to access a member using pointer
cout << "Volume of Box1: " << ptrBox->Volume() <<
endl;
return 0;
}
Output:
“this” pointer in C++
• It can be used to refer to the current class instance/object.
• “this” keyword represents address of current object of the class.
Syntax:
this-> instance variable=value;
Uses of this pointer:
1) When local variable’s name is same as member’s
name
2) To return reference to the calling object
“this” pointer in C++ : Example 1
#include<iostream>
using namespace std;
/* local variable is same as a member's name */
class Test
{
private:
int x;
public:
void setX (int x)
{
// The 'this' pointer is used to
retrieve the object's x
// hidden by the local variable 'x'
this->x = x;
}
void print() { cout << "x = " << x << endl;
}
};
int main()
{
Test obj;
int x = 20;
obj.setX(x);
obj.print();
return 0;
}
“this” pointer in C++ : Example 2
When a reference to a local object is returned, the returned reference can be used to chain
function calls on a single object.
#include<iostream>
using namespace std;
class Test
{
private:
int x;
int y;
public:
Test(int x = 0, int y = 0) {
this->x = x;
this->y = y;
}
Test& setX(int a) { x = a; return *this; }
Test& setY(int b) { y = b; return *this; }
void print() {
cout << "x = " << x << " y = " << y << endl;
}
};
int main()
{
Test obj1(5, 5);
// Chained function calls.
// All calls modify the same object
// as the same object is returned by
// reference
obj1.setX(10).setY(20);
obj1.print();
return 0;
}
Pointer to derived class
A pointer of one class can point to other class, but classes must be a
base and derived class, then it is possible.
To access the variable of the base class, base class pointer will be
used.
Pointer to derived class Example
class base{...};
class derived: public base{...};
base b1,*b2;
derive d1;
b2=&d1;
What will be the output of the following C++ code?
#include <iostream>
using namespace std;
class mobile
{
public:
void playRingTone()
{
cout<<"mobile ring tone"<<endl;
}
};
class samsung:public mobile
{
void playRingTone()
{
cout<<"samsung ring tone"<<endl;
}
};
class realme:public mobile
{
void playRingTone()
{
cout<<"real me ringtone"<<endl;
}
};
int main()
{
mobile *mptr;
samsung s1;
mptr=&s1;
mptr->playRingTone();
return 0;
}
A. mobile ring tone
B. samsung ring tone
C. real me rington
D. Error

More Related Content

PDF
Ch-4-Operator Overloading.pdf
PDF
Unit3_OOP-converted.pdf
PDF
Operator overloading
PDF
NIKUL SURANI
PDF
Polymorphism and Type Conversion.pdf pot
PDF
Object Oriented Programming using C++ - Part 3
PPTX
Operator overloaing
PPTX
Operator overloading
Ch-4-Operator Overloading.pdf
Unit3_OOP-converted.pdf
Operator overloading
NIKUL SURANI
Polymorphism and Type Conversion.pdf pot
Object Oriented Programming using C++ - Part 3
Operator overloaing
Operator overloading

Similar to 3. Polymorphism.pptx (20)

PPT
3d7b7 session4 c++
PPTX
Operator Overloading
PPT
Polymorphism and function overloading_new.ppt
PDF
Basics _of_Operator Overloading_Somesh_Kumar_SSTC
PDF
22 scheme OOPs with C++ BCS306B_module3.pdf
PPTX
operator overloading
PPTX
Bca 2nd sem u-4 operator overloading
PPTX
Mca 2nd sem u-4 operator overloading
PPT
Overloading
PDF
Lec 8.pdf a
PDF
Operator_Overloaing_Type_Conversion_OOPC(C++)
PPTX
Operator overloading
PPTX
PDF
Operator overloading
PPTX
Operator overloadng
PPT
Operator Overloading
PDF
overloading in C++
PDF
A COMPLETE FILE FOR C++
PDF
Oop05 6
PPTX
Cpp (C++)
3d7b7 session4 c++
Operator Overloading
Polymorphism and function overloading_new.ppt
Basics _of_Operator Overloading_Somesh_Kumar_SSTC
22 scheme OOPs with C++ BCS306B_module3.pdf
operator overloading
Bca 2nd sem u-4 operator overloading
Mca 2nd sem u-4 operator overloading
Overloading
Lec 8.pdf a
Operator_Overloaing_Type_Conversion_OOPC(C++)
Operator overloading
Operator overloading
Operator overloadng
Operator Overloading
overloading in C++
A COMPLETE FILE FOR C++
Oop05 6
Cpp (C++)
Ad

Recently uploaded (20)

PDF
Microbial disease of the cardiovascular and lymphatic systems
PDF
Abdominal Access Techniques with Prof. Dr. R K Mishra
PDF
Supply Chain Operations Speaking Notes -ICLT Program
PDF
Anesthesia in Laparoscopic Surgery in India
PDF
VCE English Exam - Section C Student Revision Booklet
PDF
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
PPTX
Cell Types and Its function , kingdom of life
PDF
O5-L3 Freight Transport Ops (International) V1.pdf
PDF
Module 4: Burden of Disease Tutorial Slides S2 2025
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PDF
STATICS OF THE RIGID BODIES Hibbelers.pdf
PPTX
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
PDF
O7-L3 Supply Chain Operations - ICLT Program
PDF
01-Introduction-to-Information-Management.pdf
PPTX
human mycosis Human fungal infections are called human mycosis..pptx
PDF
2.FourierTransform-ShortQuestionswithAnswers.pdf
PDF
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
PDF
RMMM.pdf make it easy to upload and study
PPTX
Cell Structure & Organelles in detailed.
PDF
FourierSeries-QuestionsWithAnswers(Part-A).pdf
Microbial disease of the cardiovascular and lymphatic systems
Abdominal Access Techniques with Prof. Dr. R K Mishra
Supply Chain Operations Speaking Notes -ICLT Program
Anesthesia in Laparoscopic Surgery in India
VCE English Exam - Section C Student Revision Booklet
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
Cell Types and Its function , kingdom of life
O5-L3 Freight Transport Ops (International) V1.pdf
Module 4: Burden of Disease Tutorial Slides S2 2025
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
STATICS OF THE RIGID BODIES Hibbelers.pdf
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
O7-L3 Supply Chain Operations - ICLT Program
01-Introduction-to-Information-Management.pdf
human mycosis Human fungal infections are called human mycosis..pptx
2.FourierTransform-ShortQuestionswithAnswers.pdf
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
RMMM.pdf make it easy to upload and study
Cell Structure & Organelles in detailed.
FourierSeries-QuestionsWithAnswers(Part-A).pdf
Ad

3. Polymorphism.pptx

  • 2. Topics Covered Polymorphism : functions overloading, overloading unary operators, overloading binary operators, virtual base classes, abstract classes, pointer to object, this pointer, pointer to derived class, virtual function, pure virtual function
  • 5.  Functions overloading  same function name but different parameters.  same function name with different signature  example of polymorphism(compile time)  overloaded functions should be there in same class.
  • 6. Area getArea() getArea() Area = w × h w = width h = height getArea() Area = π × r2  Area of Shapes using function overloading
  • 7.  Area of Shapes using function overloading
  • 8. Operator overloading Operator overloading is a compile-time polymorphism in which the operator is overloaded to provide the special meaning to the user- defined data type. • You can redefine built in operators except few: • Scope resolution operator (::) • sizeof • member selector(.) • member pointer selector(.*) • ternary operator(?:)
  • 10. Consider this example class A { }; int main() { A a1,a2,a3; a3= a1 + a2; return 0; } This is not allowed, because the addition operator “+” is predefined to operate only on built-in data types. But here, “class A” is a user-defined type, so the compiler generates an error. This is where the concept of “Operator overloading” comes in.
  • 11. Operator Overloading Syntax: return_type operator operator_Symbol(parameters) { } Example: class A { public: A operator +(A const &obj) { } };
  • 12. Operator overloading for Unary operators: The unary operators operate on a single operand : • The increment (++) and decrement (--) operators. • The unary minus (-) operator. • The logical not (!) operator.
  • 13. Operator overloading for binary operators: The binary operators operate on two operands : +, -, *, /, % a+b
  • 14. Rules for Operator Overloading Existing operators can only be overloaded. The overloaded operator contains at least one operand of the user-defined data type. When unary operators are overloaded through a member function take no explicit arguments, but, if they are overloaded by a friend function, takes one argument. When binary operators are overloaded through a member function takes one explicit argument, and if they are overloaded through a friend function takes two explicit arguments.
  • 15. Overloading Unary Operator (using member function): Example 1: Overload minus (-) unary operator. • In unary operator function, no arguments should be passed. • It works only with one class objects. • It is an overloading of an operator operating on a single operand. Class: Assume that class Distance takes two data-members i.e. feet and inches. Overload operator – Create an operator function for unary minus operator (having single operand of Distance Type) Operator function (-) will change the sign of distance Object.
  • 16. Overloading Unary Operator: Output: class Distance { public: // Data Members int feet, inch; // Constructor to initialize the object's value Distance(int f, int i) { this->feet = f; this->inch = i; } // Overloading(-) operator to perform decrement void operator-() { this->feet = -f; this->inch = -i; cout << "nFeet & Inches(Decrement):n" cout << feet << "'" << inch; } }; // Main Code int main() { // Declare and Initialize // the constructor Distance d1(8, -9); // Use (-) unary operator by // Single operand -d1; return 0; } Feet & Inches(Decrement): -8'9
  • 17. Overloading Unary Operator (using member function): Example 2: Overload unary ++ Operator (both prefix and postfix fashion)
  • 18. Binary Operator Overloading (using member function): • In binary operator overloading function, there should be one argument to be passed. • It is overloading of an operator operating on two operands. Example: Example of class Distance, add two distance objects using binary + operator class Distance { public: // Data Members int feet, inch; // No Parameter/Default Constructor Distance() { this->feet = 0; this->inch = 0; } // Parameterized Constructor Distance(int f, int i) { this->feet = f; this->inch = i; } // Overloading (+) operator to perform addition // of two Distance objects Distance operator+(Distance &d2) { // Create an object to return Distance d3; // Perform addition of feet and inches d3.feet = this->feet + d2.feet; d3.inch = this->inch + d2.inch; // Return the resulting object return d3; } };
  • 19. Binary Operator Overloading (using member function): Example Continue... Output: // Main Function Code int main() { // Declaring and Initializing first object Distance d1(8, 9); // Declaring and Initializing second object Distance d2(10, 2); // Declaring third object Distance d3; // Use overloaded operator d3 = d1 + d2; // Display the result cout << "nTotal Feet & Inches:n" cout << d3.feet << "'" << d3.inch; return 0; } Total Feet & Inches: 18'11
  • 20. Binary Operator Overloading (using member function): Example Continue... (Pictorial View of working of Binary Operator: )
  • 21. Overloading Binary Assignment (=) Operator • Overload the assignment operator (=) just as you can other operators and it can be used to create an object just like the copy constructor. class Distance { private: int feet, inches; public: // required constructors Distance() { this->feet = 0; this->inches = 0; } Distance(int f, int i) { this->feet = f; this->inches = i; } void operator = (const Distance &D2 ) { this->feet = D2.feet; this->inches = D2.inches; } // method to display distance void displayDistance() { cout << "F: " << feet << " I:" << inches << endl; } }; int main() { Distance D1(11, 10), D2(5, 11); cout << "First Distance : "; D1.displayDistance(); cout << "Second Distance :"; D2.displayDistance(); // use assignment operator D1 = D2; cout << "First Distance :"; D1.displayDistance(); return 0; }
  • 22. Overloading Binary Operator (Using Friend Function) • In this approach, the operator overloading function must precede with friend keyword, and declare a function class scope. • Keeping in mind, friend operator function takes two parameters in a binary operator, varies one parameter in a unary operator. • All the working and implementation would same as binary operator function except this function will be implemented outside of the class scope.
  • 23. Overloading Binary Operator (Using Friend Function) Example: Example using the friend function to overload binary + operator. class Distance { public: // Data Members int feet, inch; // No Parameter Constructor Distance() { this->feet = 0; this->inch = 0; } // Constructor to initialize the object's value // Parameterized Constructor Distance(int f, int i) { this->feet = f; this->inch = i; } // Declaring friend function using friend keyword friend Distance operator+(Distance&, Distance&); }; // Implementing friend function with two parameters Distance operator+(Distance& d1, Distance& d2) // Call by reference { // Create an object to return Distance d3; // Perform addition of feet and inches d3.feet = d1.feet + d2.feet; d3.inch = d1.inch + d2.inch; // Return the resulting object return d3; }
  • 24. Overloading Binary Operator (Using Friend Function) Example Continue... Output: // Main Program Code int main() { // Declaring and Initializing first object Distance d1(8, 9); // Declaring and Initializing second object Distance d2(10, 2); // Declaring third object Distance d3; // Use overloaded operator d3 = d1 + d2; // Display the result cout << "nTotal Feet & Inches:n " cout << d3.feet << "'" << d3.inch; return 0; } Total Feet & Inches: 18'11
  • 25. Operators that cannot be overloaded using Friend Function Following are the operators for which overloading is not possible in C++ using friend function: 1. function call operator () 2. assignment operator = 3. class member access operator -> 4. subscripting operator [ ] If these operators are overloaded using friend function, then program will result with compilation error. These operators can be overloaded if they are part of member functions. NOTE: A friend function is a non-member function of the class to which it has been defined as friend. Therefore, it just uses the functionality (functions and data) of the class. So, it does not consist the implementation for that class. That's why it cannot be used to overload certain class specific operators as listed above.
  • 26. Virtual Base class Introduce
  • 27. Virtual Base Class • Virtual base classes are used in virtual inheritance in a way of preventing multiple “instances” of a given class appearing in an inheritance hierarchy when using multiple inheritances. Need for Virtual Base Classes: Consider the situation where we have one class A. This class is A is inherited by two other classes B and C. Both these class are inherited into another in a new class D as shown in figure below.
  • 28. Student Exam Project Result regNo, Name studentDetails() regNo, Name studentDetails() regNo, Name studentDetails() regNo, Name studentDetails() ambiguity arises as to which data/function member would be called? Situation
  • 29. Virtual Base Class How to resolve this issue? • To resolve this ambiguity when class A is inherited in both class B and class C, it is declared as virtual base class by placing a keyword virtual. • Virtual base classes offer a way to save space and avoid ambiguities in class hierarchies that use multiple inheritances. • Note: virtual can be written before or after the public. Now only one copy of data/function member will be copied to class C and class B and class A becomes the virtual base class.
  • 30. Virtual Base Class : An Example Without Virtual, ambiguity leads to a Compiler Error With Virtual Base Class A, No ambiguity, Program runs fine!
  • 31. • Function Overriding (Run-time Polymorphism) • Virtual Function Introduce
  • 32. Function Overriding – Run-time Polymorphism • It is the redefinition of base class function in its derived class with same signature i.e., return type and parameters are exactly the same in both base and derived classes. • Suppose, the same function is defined in both the derived class and the based class. Now if we call this function using the object of the derived class, the function of the derived class is executed. This is known as function overriding in C++. The function in derived class overrides the function in base class.
  • 34. Function Overriding : Call Overridden Function Using Pointer #include <iostream> using namespace std; class Base { public: void print() { cout << "Base Function" << endl; } }; class Derived : public Base { public: void print() { cout << "Derived Function" << endl; } }; int main() { Derived derived1; // pointer of Base type that points to derived1 Base* ptr = &derived1; // call function of Base class using ptr ptr->print(); return 0; }
  • 35. Function Overriding : Call Overridden Function Using Pointer • In last program, we have created a pointer of Base type named ptr. This pointer points to the Derived object derived1 • When we call the print() function using ptr, it calls the overridden function from Base. • This is because even though ptr points to a Derived object, it is actually of Base type. So, it calls the member function of Base. • In order to override the Base function instead of accessing it, we need to use virtual functions in the Base class.
  • 36. Problems in method overriding : Need of Virtual Function • Overriding using base class pointer compiler don’t know about pointer which address is pointing because address will be decided at run time when memory will be allocated. • To over come this problem, we use virtual function. • With the help of virtual function, we can override function at run time
  • 37. Virtual Function in C++ • A virtual function is a member function which is declared within a base class and is re-defined (overridden) by a derived class. When you refer to a derived class object using a pointer or a reference to the base class, you can call a virtual function for that object and execute the derived class’s version of the function.  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.
  • 38. Rules for Virtual Functions • Virtual functions should be accessed using pointer or reference of base class type to achieve runtime polymorphism. • The prototype of virtual functions should be the same in the base as well as derived class. • They are always defined in the base class and overridden in a derived class. It is not mandatory for the derived class to override (or re-define the virtual function), in that case, the base class version of the function is used.
  • 39. Virtual Function : Example #include<iostream> using namespace std; class base { public: virtual void print() { cout << "print base classn"; } void show() { cout << "show base classn"; } }; class derived : public base { public: void print() { cout << "print derived classn"; } void show() { cout << "show derived classn"; } }; int main() { base *bptr; derived d; bptr = &d; // Virtual function, binded at runtime bptr->print(); // Non-virtual function, binded at compile time bptr->show(); return 0; }
  • 40. Pure Virtual Function in C++ • Sometimes implementation of all function cannot be provided in a base class because we don’t know the implementation. • For example, let Shape be a base class. We cannot provide implementation of function draw() in Shape, but we know every derived class must have implementation of draw(). • A pure virtual function (or abstract function) in C++ is a virtual function for which we don’t have an implementation in base class, we only declare it. A pure virtual function is declared by assigning 0 in the declaration. • We generally override a pure virtual function of base class into its derived class to provide an implementation.
  • 41. Pure Virtual Function : Example 1 int main() { Derived d; d.fun(); return 0; } #include<iostream> using namespace std; class Base { int x; public: virtual void fun() = 0; int getX() { x =10; return x; } }; // This class inherits from Base and implements fun() class Derived: public Base { int y; public: void fun() { cout << “Value of x = ” << getX(); } }; Output: Value of x = 10
  • 42. Pure Virtual Function : Example 2 class Shape { protected: float dimension; public: void getDimension() { cin >> dimension; } // pure virtual Function virtual float calculateArea() = 0; }; // Derived class class Square : public Shape { public: float calculateArea() { return dimension * dimension; } }; // Derived class class Circle : public Shape { public: float calculateArea() { return 3.14 * dimension * dimension; } }; int main() { Square square; Circle circle; cout << "Enter the length of the square: "; square.getDimension(); cout << "Area of square: " << square.calculateArea() << endl; cout << "nEnter radius of the circle: "; circle.getDimension(); cout << "Area of circle: " << circle.calculateArea() << endl; return 0; }
  • 43. Virtual Function Vs Pure Virtual Function
  • 44. Virtual Function Vs Pure Virtual Function
  • 45. Abstract Class and Pure Virtual function
  • 46. Abstract Class in C++ • In C++, A class is abstract if it has at least one pure virtual function. // An abstract class class Test { // Data members of class public: // Pure Virtual Function virtual void show() = 0; /* Other members */ }; In the above example, Test is an abstract class because it has a pure virtual function show().
  • 47. Abstract Class in C++ • An abstract class cannot be instantiated – meaning that we cannot create objects of abstract class. // pure virtual functions make a class abstract class Test { int x; public: virtual void show() = 0; int getX() { return x; } }; int main() { Test t; return 0; }
  • 48. Abstract Class in C++ • Although we cannot have object of abstract class, but we can have pointers and references of abstract class type. class Base { public: virtual void show() = 0; }; class Derived: public Base { public: void show() { cout << "In Derived n"; } }; int main(void) { Base *bp = new Derived(); bp->show(); return 0; }
  • 49. Abstract Class in C++ • If we do not override pure virtual function of base class in its derived class, then derived class also becomes abstract class. -- Since Base has a pure virtual function show(), so it is an abstract class. -- We did not override pure virtual function show() into Derived class, so it is also abstract class. -- Clearly, both Base and Derived are abstract classes here. #include<iostream> using namespace std; class Base { public: virtual void show() = 0; }; class Derived : public Base { // Empty Derived class }; int main() { Derived d; return 0; }
  • 50. Summary of Important Points about Abstract Class 1. A class is abstract if it has at least one pure virtual function. 2. If we do not override the pure virtual function in derived class, then derived class also becomes abstract class. 3. We cannot create objects of abstract classes. 4. We can create pointers and references of abstract class type. 5. An abstract class can have constructors.
  • 51. What will be the output of the following C++ code? #include<iostream> using namespace std; class Mobile { long int contactno; public: virtual void getStatus() = 0; Mobile() { contactno=9898989890; cout<<contactno; } }; class Person: public Mobile { public: void getDetails() { cout << “Blocked”; } }; int main() { Person p; p.getDetails(); return 0; } MCQ A. 9898989890 B. Blocked C.9898989890 Blocked D. Error
  • 52. What will be the output of the following C++ code? #include<iostream> using namespace std; class Mobile { long int contactno; public: virtual void getStatus() = 0; Mobile() { contactno=9898989890; cout<<contactno; } }; class Person: public Mobile { public: void getStatus(){ cout <<“ Blocked”; } void getDetails() { cout << “ Welcome”; } }; int main() { Person p; p.getDetails(); return 0; } MCQ A. 9898989890 Welcome B. Blocked C.9898989890 Blocked D. Error
  • 53. Pointer to object • A variable that holds an address value is called a pointer variable. • Just like other pointers, the object pointers are declared by placing in front of a object pointer's name. • Object can also have an address , so there is also a pointer that can point to the address of an object. That is known as pointer to an object. • It takes the following general form : class-name ∗ object-pointer ; Example : class Date { }; Date d1; Date *d2; d2=&d1; d2->functions() object pointer
  • 54. Pointer to object : An Example #include <iostream> using namespace std; class Box { double length; // Length of a box double breadth; // Breadth of a box double height; // Height of a box public: // Constructor definition Box(double l = 2.0, double b = 2.0, double h = 2.0) { cout <<"Constructor called." << endl; length = l; breadth = b; height = h; } double Volume() { return length * breadth * height; } }; int main() { Box Box1(3.3, 1.2, 1.5); // Declare box1 object Box *ptrBox; // Declare pointer to a class. // Save the address of first object ptrBox = &Box1; // Now try to access a member using pointer cout << "Volume of Box1: " << ptrBox->Volume() << endl; return 0; } Output:
  • 55. “this” pointer in C++ • It can be used to refer to the current class instance/object. • “this” keyword represents address of current object of the class. Syntax: this-> instance variable=value; Uses of this pointer: 1) When local variable’s name is same as member’s name 2) To return reference to the calling object
  • 56. “this” pointer in C++ : Example 1 #include<iostream> using namespace std; /* local variable is same as a member's name */ class Test { private: int x; public: void setX (int x) { // The 'this' pointer is used to retrieve the object's x // hidden by the local variable 'x' this->x = x; } void print() { cout << "x = " << x << endl; } }; int main() { Test obj; int x = 20; obj.setX(x); obj.print(); return 0; }
  • 57. “this” pointer in C++ : Example 2 When a reference to a local object is returned, the returned reference can be used to chain function calls on a single object. #include<iostream> using namespace std; class Test { private: int x; int y; public: Test(int x = 0, int y = 0) { this->x = x; this->y = y; } Test& setX(int a) { x = a; return *this; } Test& setY(int b) { y = b; return *this; } void print() { cout << "x = " << x << " y = " << y << endl; } }; int main() { Test obj1(5, 5); // Chained function calls. // All calls modify the same object // as the same object is returned by // reference obj1.setX(10).setY(20); obj1.print(); return 0; }
  • 58. Pointer to derived class A pointer of one class can point to other class, but classes must be a base and derived class, then it is possible. To access the variable of the base class, base class pointer will be used.
  • 59. Pointer to derived class Example class base{...}; class derived: public base{...}; base b1,*b2; derive d1; b2=&d1;
  • 60. What will be the output of the following C++ code? #include <iostream> using namespace std; class mobile { public: void playRingTone() { cout<<"mobile ring tone"<<endl; } }; class samsung:public mobile { void playRingTone() { cout<<"samsung ring tone"<<endl; } }; class realme:public mobile { void playRingTone() { cout<<"real me ringtone"<<endl; } }; int main() { mobile *mptr; samsung s1; mptr=&s1; mptr->playRingTone(); return 0; } A. mobile ring tone B. samsung ring tone C. real me rington D. Error