SlideShare a Scribd company logo
SOMESH KUMAR DEWANGAN DEPARTMENT OF CSE 1
SHRI SHANKARACHARYA TECHNICAL CAMPUS
UNIT IV
Operator Overloading
Operator overloading is a feature in C++ that allows developers to redefine the behavior of
operators for user-defined types, such as classes. This means you can make objects of your
classes respond to operators like +, -, ==, and even << in custom ways, similar to how built-
in data types behave.
Why Use Operator Overloading?
1. Intuitive Code: With operator overloading, you can write code that’s more readable
and closer to natural language, which is especially useful in cases where you’re
dealing with mathematical or logical objects.
2. Consistency: Overloading makes using custom data types feel consistent with using
built-in types, which can reduce errors and make the code easier to understand and
maintain.
3. Encapsulation: By embedding operator functionality within classes, you keep
operations related to a specific data type encapsulated, following object-oriented
principles.
Basic Concepts and Rules of Operator Overloading
1. Operators that can be Overloaded:
o Almost all operators can be overloaded, including arithmetic (+, -, *, /),
relational (==, !=, <, >), assignment (=), and stream (<<, >>) operators.
o Some operators, however, cannot be overloaded. These include:
▪ . (member access)
▪ .* (pointer-to-member access)
▪ :: (scope resolution)
▪ ?: (ternary conditional)
▪ sizeof (object size calculation)
2. Syntax of Operator Overloading:
o Operator overloading is done by defining a special function using the operator
keyword followed by the operator symbol, for example: operator+,
operator==, etc.
o Overloaded operators can be implemented as either member functions or
friend functions.
3. Operator Overloading with Member Functions vs. Friend Functions:
o Member functions: The left operand must be an object of the class. For
example, to overload + as a member function, you might write:
SOMESH KUMAR DEWANGAN DEPARTMENT OF CSE 2
SHRI SHANKARACHARYA TECHNICAL CAMPUS
Complex operator+(const Complex& other) const;
o Friend functions: These can be used if the left operand is not an object of the
class (e.g., a built-in type). Friend functions allow more flexibility in operator
overloading.
4. Overloading Unary and Binary Operators:
o Unary Operators: Operators like +, -, ++, and -- that operate on a single
operand can be overloaded with one argument (if defined outside the class) or
no arguments (if defined inside the class).
o Binary Operators: Operators like +, -, *, /, and == that operate on two
operands can be overloaded with two arguments (if defined outside the class)
or one argument (if defined inside the class).
5. Rules and Limitations:
o Precedence and Associativity: Overloading does not change the precedence or
associativity of operators.
o Operator Overloading Does Not Alter Default Behavior: You cannot create
new operators or change the fundamental behavior of operators, such as the
number of operands.
o Return Types: The return type of an overloaded operator function should
match the operation it represents. For example, an overloaded + operator
usually returns a new object of the same type as the class.
Overloading Various Operators
Overloading the + Operator for a Complex Number Class
The + operator is overloaded to add two complex numbers by adding their real and imaginary
parts separately.
#include <iostream>
using namespace std;
class Complex {
double real, imag;
public:
Complex(double r = 0, double i = 0) : real(r), imag(i) {}
SOMESH KUMAR DEWANGAN DEPARTMENT OF CSE 3
SHRI SHANKARACHARYA TECHNICAL CAMPUS
// Overload the '+' operator
Complex operator+(const Complex& other) const {
return Complex(real + other.real, imag + other.imag);
}
void display() const {
cout << real << " + " << imag << "i" << endl;
}
};
int main() {
Complex c1(3.5, 2.5), c2(1.5, 4.0);
Complex c3 = c1 + c2; // Uses overloaded '+' operator
c3.display(); // Output: 5 + 6.5i
}
the + operator is overloaded to add the real and imag parts of Complex numbers. This makes
adding complex numbers as intuitive as adding primitive types.
Overloading the - Operator for a Vector Class
Here, we overload the - operator to subtract two vectors (each with x, y, and z components).
#include <iostream>
using namespace std;
class Vector {
double x, y, z;
public:
Vector(double x_val = 0, double y_val = 0, double z_val = 0) : x(x_val), y(y_val), z(z_val)
{}
// Overload the '-' operator
Vector operator-(const Vector& other) const {
SOMESH KUMAR DEWANGAN DEPARTMENT OF CSE 4
SHRI SHANKARACHARYA TECHNICAL CAMPUS
return Vector(x - other.x, y - other.y, z - other.z);
}
void display() const {
cout << "Vector(" << x << ", " << y << ", " << z << ")" << endl;
}
};
int main() {
Vector v1(5.0, 3.0, 2.0), v2(1.0, 1.5, 0.5);
Vector v3 = v1 - v2; // Uses overloaded '-' operator
v3.display(); // Output: Vector(4, 1.5, 1.5)
}
the - operator is overloaded to perform vector subtraction, allowing for intuitive vector
manipulation.
Overloading the == Operator for a Distance Class
The == operator can be overloaded to compare two Distance objects by checking if both their
feet and inches values are equal.
#include <iostream>
using namespace std;
class Distance {
int feet;
double inches;
public:
Distance(int f = 0, double i = 0.0) : feet(f), inches(i) {}
// Overload the '==' operator
bool operator==(const Distance& other) const {
return (feet == other.feet && inches == other.inches);
}
SOMESH KUMAR DEWANGAN DEPARTMENT OF CSE 5
SHRI SHANKARACHARYA TECHNICAL CAMPUS
void display() const {
cout << feet << " feet " << inches << " inches" << endl;
}
};
int main() {
Distance d1(5, 9.5), d2(5, 9.5), d3(6, 4.0);
if (d1 == d2) {
cout << "d1 is equal to d2" << endl;
}
if (!(d1 == d3)) {
cout << "d1 is not equal to d3" << endl;
}
}
the == operator to compare if two Distance objects are equal, enhancing readability when
comparing complex data types.
Overloading the << (Insertion) Operator for Outputting Objects
The << operator is typically used for outputting data to the console. We can overload it to
print the contents of a Point class object directly.
#include <iostream>
using namespace std;
class Point {
int x, y;
public:
Point(int x_val = 0, int y_val = 0) : x(x_val), y(y_val) {}
// Overload the '<<' operator
friend ostream& operator<<(ostream& out, const Point& p) {
out << "(" << p.x << ", " << p.y << ")";
SOMESH KUMAR DEWANGAN DEPARTMENT OF CSE 6
SHRI SHANKARACHARYA TECHNICAL CAMPUS
return out;
}
};
int main() {
Point p1(3, 4), p2(5, 7);
cout << "Point p1: " << p1 << endl; // Uses overloaded '<<' operator
cout << "Point p2: " << p2 << endl;
}
By overloading the << operator, we can print Point objects in a more readable format, making
it simpler to debug and display information.
Overloading the [] Operator for a Custom Array Class
The [] operator can be overloaded to provide array-like access to elements within a custom
array class.
cpp
Copy code
#include <iostream>
using namespace std;
class IntArray {
int arr[5];
public:
IntArray() {
for (int i = 0; i < 5; ++i)
arr[i] = 0;
}
// Overload the '[]' operator
int& operator[](int index) {
if (index >= 0 && index < 5)
SOMESH KUMAR DEWANGAN DEPARTMENT OF CSE 7
SHRI SHANKARACHARYA TECHNICAL CAMPUS
return arr[index];
else {
cout << "Index out of bounds" << endl;
exit(1);
}
}
void display() const {
for (int i = 0; i < 5; ++i)
cout << arr[i] << " ";
cout << endl;
}
};
int main() {
IntArray array;
array[0] = 10; // Uses overloaded '[]' operator
array[1] = 20;
array.display(); // Output: 10 20 0 0 0
}
the [] operator is overloaded to access and modify elements of a custom array class, giving it
array-like behavior and improving code readability.
Overloading the ++ Operator for Incrementing
The ++ operator can be overloaded to increment values, similar to its behavior with built-in
types.
#include <iostream>
using namespace std;
class Counter {
int value;
public:
Counter(int v = 0) : value(v) {}
SOMESH KUMAR DEWANGAN DEPARTMENT OF CSE 8
SHRI SHANKARACHARYA TECHNICAL CAMPUS
// Overload the '++' operator (prefix)
Counter& operator++() {
++value;
return *this;
}
// Overload the '++' operator (postfix)
Counter operator++(int) {
Counter temp = *this;
++value;
return temp;
}
void display() const {
cout << "Counter value: " << value << endl;
}
};
int main() {
Counter c(5);
++c; // Uses overloaded prefix '++'
c.display(); // Output: Counter value: 6
c++; // Uses overloaded postfix '++'
c.display(); // Output: Counter value: 7
}
Type Conversion:
Type conversion in C++ refers to converting one data type into another. This can involve both
basic types (e.g., int, float) and user-defined types (e.g., classes). There are different types of
conversions in C++:
SOMESH KUMAR DEWANGAN DEPARTMENT OF CSE 9
SHRI SHANKARACHARYA TECHNICAL CAMPUS
1. Implicit Conversion (Automatic Conversion): Performed automatically by the
compiler. For instance, when you assign an int to a float, the compiler automatically
converts it.
2. Explicit Conversion (Casting): When conversions need to be made explicitly, as in
static_cast, reinterpret_cast, const_cast, or dynamic_cast.
3. User-Defined Conversion: These are conversions defined by the programmer within
a class, allowing objects of that class to be converted to and from other types.
User-Defined Type Conversion
C++ supports user-defined type conversions to make class objects behave like built-in types
in certain situations. These conversions can be classified into:
1. Basic Type to Class Type Conversion: Converting a basic data type (like int, float,
etc.) to a user-defined class type.
2. Class Type to Basic Type Conversion: Converting an object of a class type to a basic
data type.
3. Class Type to Another Class Type Conversion: Converting an object of one class to
an object of another class.
1. Basic Type to Class Type Conversion
This is achieved by creating a constructor in the class that takes the basic type as a parameter.
The compiler will use this constructor to convert the basic type to the class type.
#include <iostream>
using namespace std;
class Distance {
int feet;
double inches;
public:
// Constructor that takes a single int parameter to convert from basic type to class type
Distance(int totalInches) {
feet = totalInches / 12;
inches = totalInches % 12;
}
void display() const {
cout << feet << " feet " << inches << " inches" << endl;
}
};
SOMESH KUMAR DEWANGAN DEPARTMENT OF CSE 10
SHRI SHANKARACHARYA TECHNICAL CAMPUS
int main() {
Distance d = 37; // 37 inches automatically converts to Distance object
d.display(); // Output: 3 feet 1 inches
}
Here, the constructor Distance(int totalInches) allows int to be automatically converted to a
Distance object. When 37 is assigned to d, this constructor is invoked to convert it into a
Distance instance.
2. Class Type to Basic Type Conversion
For this conversion, you define a conversion operator in the class. The operator keyword is
used to define the type to which the class object should be converted.
#include <iostream>
using namespace std;
class Distance {
int feet;
double inches;
public:
Distance(int f, double i) : feet(f), inches(i) {}
// Conversion operator to convert Distance to int
operator int() const {
return feet * 12 + inches; // Converts Distance object to total inches
}
};
int main() {
Distance d(3, 4.5);
int inches = d; // Converts Distance object to int
cout << "Distance in inches: " << inches << endl; // Output: Distance in inches: 40
}
operator int() allows the Distance object d to be converted to int. When assigned to inches,
the compiler uses this conversion operator to obtain the equivalent integer.
3. Class Type to Another Class Type Conversion
To convert an object from one class to another, you can either define a conversion constructor
in the destination class or define a conversion operator in the source class.
SOMESH KUMAR DEWANGAN DEPARTMENT OF CSE 11
SHRI SHANKARACHARYA TECHNICAL CAMPUS
SOMESH KUMAR DEWANGAN DEPARTMENT OF CSE 12
SHRI SHANKARACHARYA TECHNICAL CAMPUS
Using Conversion Constructor in Destination Class
#include <iostream>
using namespace std;
class Distance {
int feet;
double inches;
public:
Distance(int f, double i) : feet(f), inches(i) {}
int getFeet() const { return feet; }
double getInches() const { return inches; }
};
class MetricDistance {
double meters;
public:
// Conversion constructor that takes a Distance object
MetricDistance(const Distance& d) {
meters = (d.getFeet() * 12 + d.getInches()) * 0.0254; // Convert to meters
}
void display() const {
cout << meters << " meters" << endl;
}
};
int main() {
Distance d(3, 3.5);
MetricDistance md = d; // Converts Distance to MetricDistance using conversion
constructor
md.display(); // Output: 1.0049 meters
}
SOMESH KUMAR DEWANGAN DEPARTMENT OF CSE 13
SHRI SHANKARACHARYA TECHNICAL CAMPUS
the MetricDistance class has a conversion constructor that takes a Distance object. This
constructor converts Distance to MetricDistance by calculating the equivalent metric value in
meters.
Important Points to Note
1. Automatic Conversion Risks: Be cautious with user-defined conversions, as they
may lead to ambiguous code or unexpected results when the compiler performs
automatic conversions.
2. Explicit Keyword: C++11 introduced the explicit keyword for constructors to
prevent unintended implicit conversions. When a constructor is marked explicit, it
cannot be used for implicit conversions.
Example with explicit Keyword
class Distance {
public:
explicit Distance(int totalInches) { /*...*/ }
};
Using explicit prevents the constructor from being used in implicit conversions, so Distance d
= 37; would result in an error unless explicitly cast: Distance d = Distance(37);
SOMESH KUMAR DEWANGAN DEPARTMENT OF CSE 14
SHRI SHANKARACHARYA TECHNICAL CAMPUS
Inheritance
Inheritance in C++ is a powerful object-oriented programming (OOP) feature that lets one
class inherit the properties and behaviors of another class. This enables code reuse,
modularity, and the formation of hierarchical class structures. Here’s a detailed explanation of
inheritance concepts, including defining derived classes, forms of inheritance, handling
ambiguity in multiple and multipath inheritance, virtual base classes, object slicing, function
overriding, and constructor/destructor execution order.
1. Introduction to Inheritance
Inheritance allows a derived class to acquire properties and behaviors (data members and
methods) of a base class. This establishes an "is-a" relationship between classes, meaning a
derived class can be considered a more specific version of a base class.
For example:
• A Car class can inherit from a Vehicle class, because a car "is-a" vehicle.
• Inheritance enables the derived class to extend or modify the base class functionality.
2. Defining Derived Classes
In C++, a derived class is created by using the following syntax:
cpp
Copy code
class DerivedClass : access_specifier BaseClass {
// Additional members and functions specific to DerivedClass
};
• access_specifier (usually public, protected, or private) controls the inheritance
visibility of base class members in the derived class.
• The derived class inherits all the accessible members of the base class.
Example:
cpp
Copy code
#include <iostream>
using namespace std;
SOMESH KUMAR DEWANGAN DEPARTMENT OF CSE 15
SHRI SHANKARACHARYA TECHNICAL CAMPUS
class Animal {
public:
void eat() { cout << "Eating..." << endl; }
};
class Dog : public Animal { // Dog is derived from Animal
public:
void bark() { cout << "Barking..." << endl; }
};
int main() {
Dog d;
d.eat(); // Inherited from Animal
d.bark(); // Defined in Dog
return 0;
}
3. Forms of Inheritance
There are several forms of inheritance in C++:
• Single Inheritance: A derived class inherits from one base class.
• Multiple Inheritance: A derived class inherits from more than one base class.
• Multilevel Inheritance: A class derives from a class, which is also derived from
another class, creating a chain.
• Hierarchical Inheritance: Multiple classes inherit from a single base class.
• Hybrid Inheritance: A combination of multiple and multilevel inheritance (can lead
to ambiguity, resolved by virtual inheritance).
In C++, inheritance can take several forms, each representing a different kind of
relationship between base and derived classes. Here’s a breakdown of the different forms
of inheritance, along with examples for clarity:
1. Single Inheritance
SOMESH KUMAR DEWANGAN DEPARTMENT OF CSE 16
SHRI SHANKARACHARYA TECHNICAL CAMPUS
Single inheritance is when a derived class inherits from only one base class. This is the
simplest form of inheritance.
Example:
cpp
Copy code
#include <iostream>
using namespace std;
class Animal {
public:
void eat() { cout << "Eating..." << endl; }
};
class Dog : public Animal { // Dog inherits from Animal
public:
void bark() { cout << "Barking..." << endl; }
};
int main() {
Dog d;
d.eat(); // Inherited from Animal
d.bark(); // Defined in Dog
return 0;
}
In this example:
• Dog is the derived class and Animal is the base class.
• Dog inherits the eat() method from Animal and adds its own method, bark().
2. Multiple Inheritance
Multiple inheritance occurs when a derived class inherits from more than one base class.
This allows the derived class to combine the functionalities of multiple base classes but
SOMESH KUMAR DEWANGAN DEPARTMENT OF CSE 17
SHRI SHANKARACHARYA TECHNICAL CAMPUS
can also introduce complexity due to potential conflicts (e.g., methods with the same
name in different base classes).
Example:
cpp
Copy code
#include <iostream>
using namespace std;
class Animal {
public:
void eat() { cout << "Eating..." << endl; }
};
class Mammal {
public:
void walk() { cout << "Walking..." << endl; }
};
class Dog : public Animal, public Mammal { // Dog inherits from both Animal and
Mammal
public:
void bark() { cout << "Barking..." << endl; }
};
int main() {
Dog d;
d.eat(); // From Animal
d.walk(); // From Mammal
d.bark(); // Defined in Dog
return 0;
}
SOMESH KUMAR DEWANGAN DEPARTMENT OF CSE 18
SHRI SHANKARACHARYA TECHNICAL CAMPUS
In this example:
• Dog inherits both eat() from Animal and walk() from Mammal.
• This showcases how Dog can combine functionality from multiple base classes.
3. Multilevel Inheritance
Multilevel inheritance occurs when a derived class serves as a base class for another
class, creating a chain of inheritance. It establishes a hierarchy where each level builds
upon the previous level.
Example:
cpp
Copy code
#include <iostream>
using namespace std;
class Animal {
public:
void eat() { cout << "Eating..." << endl; }
};
class Dog : public Animal {
public:
void bark() { cout << "Barking..." << endl; }
};
class Puppy : public Dog { // Puppy inherits from Dog, which inherits from Animal
public:
void weep() { cout << "Weeping..." << endl; }
};
int main() {
Puppy p;
SOMESH KUMAR DEWANGAN DEPARTMENT OF CSE 19
SHRI SHANKARACHARYA TECHNICAL CAMPUS
p.eat(); // Inherited from Animal
p.bark(); // Inherited from Dog
p.weep(); // Defined in Puppy
return 0;
}
In this example:
• Puppy inherits from Dog, which in turn inherits from Animal.
• Puppy has access to eat() (from Animal), bark() (from Dog), and weep() (defined in
Puppy), forming a chain of inheritance.
4. Hierarchical Inheritance
Hierarchical inheritance occurs when multiple derived classes inherit from a single base
class. This allows each derived class to share and possibly extend the properties and
behaviors of the base class.
Example:
cpp
Copy code
#include <iostream>
using namespace std;
class Animal {
public:
void eat() { cout << "Eating..." << endl; }
};
class Dog : public Animal { // Dog inherits from Animal
public:
void bark() { cout << "Barking..." << endl; }
};
class Cat : public Animal { // Cat also inherits from Animal
SOMESH KUMAR DEWANGAN DEPARTMENT OF CSE 20
SHRI SHANKARACHARYA TECHNICAL CAMPUS
public:
void meow() { cout << "Meowing..." << endl; }
};
int main() {
Dog d;
Cat c;
d.eat(); // Inherited from Animal
d.bark(); // Defined in Dog
c.eat(); // Inherited from Animal
c.meow(); // Defined in Cat
return 0;
}
In this example:
• Both Dog and Cat are derived classes that inherit from the same base class, Animal.
• Dog and Cat share the eat() method but have their own unique methods: bark() for
Dog and meow() for Cat.
5. Hybrid Inheritance
Hybrid inheritance is a combination of two or more of the above types of inheritance. It
often involves both multiple and multilevel inheritance and can lead to the diamond
problem.
Diamond Problem
The diamond problem occurs in hybrid inheritance when two derived classes inherit from
the same base class, and a further class inherits from both of them. This creates ambiguity
because the final derived class gets two copies of the base class members. Virtual
inheritance solves this problem by ensuring only one instance of the base class exists.
Example:
cpp
Copy code
#include <iostream>
using namespace std;
SOMESH KUMAR DEWANGAN DEPARTMENT OF CSE 21
SHRI SHANKARACHARYA TECHNICAL CAMPUS
class Animal {
public:
void eat() { cout << "Eating..." << endl; }
};
class Mammal : virtual public Animal { }; // Virtual inheritance
class Bird : virtual public Animal { }; // Virtual inheritance
class Bat : public Mammal, public Bird { };
int main() {
Bat b;
b.eat(); // No ambiguity due to virtual inheritance
return 0;
}
In this example:
• Animal is the base class, with Mammal and Bird as derived classes using virtual
inheritance.
• Bat inherits from both Mammal and Bird, but Animal appears only once in Bat's
hierarchy due to virtual inheritance, avoiding ambiguity.
4. Ambiguity in Multiple and Multipath Inheritance
In multiple and multipath inheritance, ambiguity may arise if two or more parent classes have
a member with the same name. This is common in complex hierarchies or "diamond-shaped"
inheritance structures, where a base class is inherited multiple times through different paths.
Example of Ambiguity:
cpp
Copy code
#include <iostream>
SOMESH KUMAR DEWANGAN DEPARTMENT OF CSE 22
SHRI SHANKARACHARYA TECHNICAL CAMPUS
using namespace std;
class A {
public:
void show() { cout << "A::show" << endl; }
};
class B : public A { };
class C : public A { };
class D : public B, public C { };
int main() {
D d;
d.show(); // Error: ambiguous because of multiple inheritance from A
return 0;
}
Here, D inherits show() from both B and C, leading to ambiguity. To resolve this, you can
specify the path explicitly:
cpp
Copy code
d.B::show();
Virtual Base Class (Resolving the Diamond Problem):
To resolve ambiguity in complex inheritance structures, use virtual inheritance. By
declaring the base class as a virtual base class, C++ ensures only one instance of the base
class exists in the derived hierarchy.
cpp
Copy code
class A {
public:
void show() { cout << "A::show" << endl; }
SOMESH KUMAR DEWANGAN DEPARTMENT OF CSE 23
SHRI SHANKARACHARYA TECHNICAL CAMPUS
};
class B : virtual public A { };
class C : virtual public A { };
class D : public B, public C { };
int main() {
D d;
d.show(); // No ambiguity due to virtual inheritance
return 0;
}
5. Object Slicing
Object slicing occurs when an object of a derived class is assigned to an object of the base
class, "slicing" off the derived part.
cpp
Copy code
#include <iostream>
using namespace std;
class Base {
public:
int x;
};
class Derived : public Base {
public:
int y;
};
SOMESH KUMAR DEWANGAN DEPARTMENT OF CSE 24
SHRI SHANKARACHARYA TECHNICAL CAMPUS
int main() {
Derived d;
d.x = 1;
d.y = 2;
Base b = d; // Object slicing occurs here
cout << b.x << endl; // Prints 1
// cout << b.y << endl; // Error: Base has no member y
return 0;
}
Here, the y member of Derived is "sliced off" when d is assigned to b. To avoid object
slicing, use pointers or references instead.
6. Overriding Member Functions
In function overriding, a derived class redefines a function of the base class. To enable
polymorphism, the base class function is declared as virtual, allowing the derived class
version to be called.
cpp
Copy code
#include <iostream>
using namespace std;
class Animal {
public:
virtual void sound() { cout << "Animal sound..." << endl; }
};
class Dog : public Animal {
public:
void sound() override { cout << "Dog barks..." << endl; }
SOMESH KUMAR DEWANGAN DEPARTMENT OF CSE 25
SHRI SHANKARACHARYA TECHNICAL CAMPUS
};
int main() {
Animal* a = new Dog();
a->sound(); // Calls Dog's sound() due to virtual function
delete a;
return 0;
}
7. Order of Execution of Constructors and Destructors
When an object of a derived class is created, the base class constructor is called first,
followed by the derived class constructor. When destructing, the derived class destructor is
called first, followed by the base class destructor. This ensures that the base part of the
derived object is fully constructed and destructed.
cpp
Copy code
#include <iostream>
using namespace std;
class Base {
public:
Base() { cout << "Base Constructor" << endl; }
~Base() { cout << "Base Destructor" << endl; }
};
class Derived : public Base {
public:
Derived() { cout << "Derived Constructor" << endl; }
~Derived() { cout << "Derived Destructor" << endl; }
};
SOMESH KUMAR DEWANGAN DEPARTMENT OF CSE 26
SHRI SHANKARACHARYA TECHNICAL CAMPUS
int main() {
Derived d;
return 0;
}
Output:
Copy code
Base Constructor
Derived Constructor
Derived Destructor
Base Destructor
In this example:
• The Base constructor is called before the Derived constructor.
• The Derived destructor is called before the Base destructor.
Ad

More Related Content

Similar to Basics _of_Operator Overloading_Somesh_Kumar_SSTC (20)

Inline function
Inline functionInline function
Inline function
Tech_MX
 
Ch-4-Operator Overloading.pdf
Ch-4-Operator Overloading.pdfCh-4-Operator Overloading.pdf
Ch-4-Operator Overloading.pdf
esuEthopi
 
Object Oriented Programming using C++: Ch08 Operator Overloading.pptx
Object Oriented Programming using C++: Ch08 Operator Overloading.pptxObject Oriented Programming using C++: Ch08 Operator Overloading.pptx
Object Oriented Programming using C++: Ch08 Operator Overloading.pptx
RashidFaridChishti
 
C++ tutorials
C++ tutorialsC++ tutorials
C++ tutorials
Divyanshu Dubey
 
6. Functions in C ++ programming object oriented programming
6. Functions in C ++ programming object oriented programming6. Functions in C ++ programming object oriented programming
6. Functions in C ++ programming object oriented programming
Ahmad177077
 
22 scheme OOPs with C++ BCS306B_module2.pdfmodule2.pdf
22 scheme  OOPs with C++ BCS306B_module2.pdfmodule2.pdf22 scheme  OOPs with C++ BCS306B_module2.pdfmodule2.pdf
22 scheme OOPs with C++ BCS306B_module2.pdfmodule2.pdf
sindhus795217
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
Pranali Chaudhari
 
C++ Interview Questions and Answers PDF By ScholarHat
C++ Interview Questions and Answers PDF By ScholarHatC++ Interview Questions and Answers PDF By ScholarHat
C++ Interview Questions and Answers PDF By ScholarHat
Scholarhat
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
Ramish Suleman
 
Week7a.pptx
Week7a.pptxWeek7a.pptx
Week7a.pptx
NasirAli233814
 
Lec 26.27-operator overloading
Lec 26.27-operator overloadingLec 26.27-operator overloading
Lec 26.27-operator overloading
Princess Sam
 
3d7b7 session4 c++
3d7b7 session4 c++3d7b7 session4 c++
3d7b7 session4 c++
Mukund Trivedi
 
Object Oriented Programming using C++ - Part 3
Object Oriented Programming using C++ - Part 3Object Oriented Programming using C++ - Part 3
Object Oriented Programming using C++ - Part 3
University College of Engineering Kakinada, JNTUK - Kakinada, India
 
Lec 28 - operator overloading
Lec 28 - operator overloadingLec 28 - operator overloading
Lec 28 - operator overloading
Princess Sam
 
22 scheme OOPs with C++ BCS306B_module3.pdf
22 scheme  OOPs with C++ BCS306B_module3.pdf22 scheme  OOPs with C++ BCS306B_module3.pdf
22 scheme OOPs with C++ BCS306B_module3.pdf
sindhus795217
 
C++ Programming
C++ ProgrammingC++ Programming
C++ Programming
Envision Computer Training Institute
 
Chapter 1 (2) array and structure r.pptx
Chapter 1 (2) array and structure r.pptxChapter 1 (2) array and structure r.pptx
Chapter 1 (2) array and structure r.pptx
abenezertekalign118
 
C++ Programming
C++ ProgrammingC++ Programming
C++ Programming
Rounak Samdadia
 
Operator Overloading
Operator OverloadingOperator Overloading
Operator Overloading
Nilesh Dalvi
 
3. Polymorphism.pptx
3. Polymorphism.pptx3. Polymorphism.pptx
3. Polymorphism.pptx
ChhaviCoachingCenter
 
Inline function
Inline functionInline function
Inline function
Tech_MX
 
Ch-4-Operator Overloading.pdf
Ch-4-Operator Overloading.pdfCh-4-Operator Overloading.pdf
Ch-4-Operator Overloading.pdf
esuEthopi
 
Object Oriented Programming using C++: Ch08 Operator Overloading.pptx
Object Oriented Programming using C++: Ch08 Operator Overloading.pptxObject Oriented Programming using C++: Ch08 Operator Overloading.pptx
Object Oriented Programming using C++: Ch08 Operator Overloading.pptx
RashidFaridChishti
 
6. Functions in C ++ programming object oriented programming
6. Functions in C ++ programming object oriented programming6. Functions in C ++ programming object oriented programming
6. Functions in C ++ programming object oriented programming
Ahmad177077
 
22 scheme OOPs with C++ BCS306B_module2.pdfmodule2.pdf
22 scheme  OOPs with C++ BCS306B_module2.pdfmodule2.pdf22 scheme  OOPs with C++ BCS306B_module2.pdfmodule2.pdf
22 scheme OOPs with C++ BCS306B_module2.pdfmodule2.pdf
sindhus795217
 
C++ Interview Questions and Answers PDF By ScholarHat
C++ Interview Questions and Answers PDF By ScholarHatC++ Interview Questions and Answers PDF By ScholarHat
C++ Interview Questions and Answers PDF By ScholarHat
Scholarhat
 
Lec 26.27-operator overloading
Lec 26.27-operator overloadingLec 26.27-operator overloading
Lec 26.27-operator overloading
Princess Sam
 
Lec 28 - operator overloading
Lec 28 - operator overloadingLec 28 - operator overloading
Lec 28 - operator overloading
Princess Sam
 
22 scheme OOPs with C++ BCS306B_module3.pdf
22 scheme  OOPs with C++ BCS306B_module3.pdf22 scheme  OOPs with C++ BCS306B_module3.pdf
22 scheme OOPs with C++ BCS306B_module3.pdf
sindhus795217
 
Chapter 1 (2) array and structure r.pptx
Chapter 1 (2) array and structure r.pptxChapter 1 (2) array and structure r.pptx
Chapter 1 (2) array and structure r.pptx
abenezertekalign118
 
Operator Overloading
Operator OverloadingOperator Overloading
Operator Overloading
Nilesh Dalvi
 

Recently uploaded (20)

Compiler Design Unit1 PPT Phases of Compiler.pptx
Compiler Design Unit1 PPT Phases of Compiler.pptxCompiler Design Unit1 PPT Phases of Compiler.pptx
Compiler Design Unit1 PPT Phases of Compiler.pptx
RushaliDeshmukh2
 
MAQUINARIA MINAS CEMA 6th Edition (1).pdf
MAQUINARIA MINAS CEMA 6th Edition (1).pdfMAQUINARIA MINAS CEMA 6th Edition (1).pdf
MAQUINARIA MINAS CEMA 6th Edition (1).pdf
ssuser562df4
 
The Gaussian Process Modeling Module in UQLab
The Gaussian Process Modeling Module in UQLabThe Gaussian Process Modeling Module in UQLab
The Gaussian Process Modeling Module in UQLab
Journal of Soft Computing in Civil Engineering
 
Machine learning project on employee attrition detection using (2).pptx
Machine learning project on employee attrition detection using (2).pptxMachine learning project on employee attrition detection using (2).pptx
Machine learning project on employee attrition detection using (2).pptx
rajeswari89780
 
Mathematical foundation machine learning.pdf
Mathematical foundation machine learning.pdfMathematical foundation machine learning.pdf
Mathematical foundation machine learning.pdf
TalhaShahid49
 
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
inmishra17121973
 
AI-assisted Software Testing (3-hours tutorial)
AI-assisted Software Testing (3-hours tutorial)AI-assisted Software Testing (3-hours tutorial)
AI-assisted Software Testing (3-hours tutorial)
Vəhid Gəruslu
 
some basics electrical and electronics knowledge
some basics electrical and electronics knowledgesome basics electrical and electronics knowledge
some basics electrical and electronics knowledge
nguyentrungdo88
 
Development of MLR, ANN and ANFIS Models for Estimation of PCUs at Different ...
Development of MLR, ANN and ANFIS Models for Estimation of PCUs at Different ...Development of MLR, ANN and ANFIS Models for Estimation of PCUs at Different ...
Development of MLR, ANN and ANFIS Models for Estimation of PCUs at Different ...
Journal of Soft Computing in Civil Engineering
 
RICS Membership-(The Royal Institution of Chartered Surveyors).pdf
RICS Membership-(The Royal Institution of Chartered Surveyors).pdfRICS Membership-(The Royal Institution of Chartered Surveyors).pdf
RICS Membership-(The Royal Institution of Chartered Surveyors).pdf
MohamedAbdelkader115
 
QA/QC Manager (Quality management Expert)
QA/QC Manager (Quality management Expert)QA/QC Manager (Quality management Expert)
QA/QC Manager (Quality management Expert)
rccbatchplant
 
Smart_Storage_Systems_Production_Engineering.pptx
Smart_Storage_Systems_Production_Engineering.pptxSmart_Storage_Systems_Production_Engineering.pptx
Smart_Storage_Systems_Production_Engineering.pptx
rushikeshnavghare94
 
Smart Storage Solutions.pptx for production engineering
Smart Storage Solutions.pptx for production engineeringSmart Storage Solutions.pptx for production engineering
Smart Storage Solutions.pptx for production engineering
rushikeshnavghare94
 
railway wheels, descaling after reheating and before forging
railway wheels, descaling after reheating and before forgingrailway wheels, descaling after reheating and before forging
railway wheels, descaling after reheating and before forging
Javad Kadkhodapour
 
Explainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptx
Explainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptxExplainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptx
Explainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptx
MahaveerVPandit
 
Avnet Silica's PCIM 2025 Highlights Flyer
Avnet Silica's PCIM 2025 Highlights FlyerAvnet Silica's PCIM 2025 Highlights Flyer
Avnet Silica's PCIM 2025 Highlights Flyer
WillDavies22
 
IntroSlides-April-BuildWithAI-VertexAI.pdf
IntroSlides-April-BuildWithAI-VertexAI.pdfIntroSlides-April-BuildWithAI-VertexAI.pdf
IntroSlides-April-BuildWithAI-VertexAI.pdf
Luiz Carneiro
 
DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...
DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...
DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...
charlesdick1345
 
Artificial Intelligence (AI) basics.pptx
Artificial Intelligence (AI) basics.pptxArtificial Intelligence (AI) basics.pptx
Artificial Intelligence (AI) basics.pptx
aditichinar
 
new ppt artificial intelligence historyyy
new ppt artificial intelligence historyyynew ppt artificial intelligence historyyy
new ppt artificial intelligence historyyy
PianoPianist
 
Compiler Design Unit1 PPT Phases of Compiler.pptx
Compiler Design Unit1 PPT Phases of Compiler.pptxCompiler Design Unit1 PPT Phases of Compiler.pptx
Compiler Design Unit1 PPT Phases of Compiler.pptx
RushaliDeshmukh2
 
MAQUINARIA MINAS CEMA 6th Edition (1).pdf
MAQUINARIA MINAS CEMA 6th Edition (1).pdfMAQUINARIA MINAS CEMA 6th Edition (1).pdf
MAQUINARIA MINAS CEMA 6th Edition (1).pdf
ssuser562df4
 
Machine learning project on employee attrition detection using (2).pptx
Machine learning project on employee attrition detection using (2).pptxMachine learning project on employee attrition detection using (2).pptx
Machine learning project on employee attrition detection using (2).pptx
rajeswari89780
 
Mathematical foundation machine learning.pdf
Mathematical foundation machine learning.pdfMathematical foundation machine learning.pdf
Mathematical foundation machine learning.pdf
TalhaShahid49
 
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
inmishra17121973
 
AI-assisted Software Testing (3-hours tutorial)
AI-assisted Software Testing (3-hours tutorial)AI-assisted Software Testing (3-hours tutorial)
AI-assisted Software Testing (3-hours tutorial)
Vəhid Gəruslu
 
some basics electrical and electronics knowledge
some basics electrical and electronics knowledgesome basics electrical and electronics knowledge
some basics electrical and electronics knowledge
nguyentrungdo88
 
RICS Membership-(The Royal Institution of Chartered Surveyors).pdf
RICS Membership-(The Royal Institution of Chartered Surveyors).pdfRICS Membership-(The Royal Institution of Chartered Surveyors).pdf
RICS Membership-(The Royal Institution of Chartered Surveyors).pdf
MohamedAbdelkader115
 
QA/QC Manager (Quality management Expert)
QA/QC Manager (Quality management Expert)QA/QC Manager (Quality management Expert)
QA/QC Manager (Quality management Expert)
rccbatchplant
 
Smart_Storage_Systems_Production_Engineering.pptx
Smart_Storage_Systems_Production_Engineering.pptxSmart_Storage_Systems_Production_Engineering.pptx
Smart_Storage_Systems_Production_Engineering.pptx
rushikeshnavghare94
 
Smart Storage Solutions.pptx for production engineering
Smart Storage Solutions.pptx for production engineeringSmart Storage Solutions.pptx for production engineering
Smart Storage Solutions.pptx for production engineering
rushikeshnavghare94
 
railway wheels, descaling after reheating and before forging
railway wheels, descaling after reheating and before forgingrailway wheels, descaling after reheating and before forging
railway wheels, descaling after reheating and before forging
Javad Kadkhodapour
 
Explainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptx
Explainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptxExplainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptx
Explainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptx
MahaveerVPandit
 
Avnet Silica's PCIM 2025 Highlights Flyer
Avnet Silica's PCIM 2025 Highlights FlyerAvnet Silica's PCIM 2025 Highlights Flyer
Avnet Silica's PCIM 2025 Highlights Flyer
WillDavies22
 
IntroSlides-April-BuildWithAI-VertexAI.pdf
IntroSlides-April-BuildWithAI-VertexAI.pdfIntroSlides-April-BuildWithAI-VertexAI.pdf
IntroSlides-April-BuildWithAI-VertexAI.pdf
Luiz Carneiro
 
DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...
DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...
DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...
charlesdick1345
 
Artificial Intelligence (AI) basics.pptx
Artificial Intelligence (AI) basics.pptxArtificial Intelligence (AI) basics.pptx
Artificial Intelligence (AI) basics.pptx
aditichinar
 
new ppt artificial intelligence historyyy
new ppt artificial intelligence historyyynew ppt artificial intelligence historyyy
new ppt artificial intelligence historyyy
PianoPianist
 
Ad

Basics _of_Operator Overloading_Somesh_Kumar_SSTC

  • 1. SOMESH KUMAR DEWANGAN DEPARTMENT OF CSE 1 SHRI SHANKARACHARYA TECHNICAL CAMPUS UNIT IV Operator Overloading Operator overloading is a feature in C++ that allows developers to redefine the behavior of operators for user-defined types, such as classes. This means you can make objects of your classes respond to operators like +, -, ==, and even << in custom ways, similar to how built- in data types behave. Why Use Operator Overloading? 1. Intuitive Code: With operator overloading, you can write code that’s more readable and closer to natural language, which is especially useful in cases where you’re dealing with mathematical or logical objects. 2. Consistency: Overloading makes using custom data types feel consistent with using built-in types, which can reduce errors and make the code easier to understand and maintain. 3. Encapsulation: By embedding operator functionality within classes, you keep operations related to a specific data type encapsulated, following object-oriented principles. Basic Concepts and Rules of Operator Overloading 1. Operators that can be Overloaded: o Almost all operators can be overloaded, including arithmetic (+, -, *, /), relational (==, !=, <, >), assignment (=), and stream (<<, >>) operators. o Some operators, however, cannot be overloaded. These include: ▪ . (member access) ▪ .* (pointer-to-member access) ▪ :: (scope resolution) ▪ ?: (ternary conditional) ▪ sizeof (object size calculation) 2. Syntax of Operator Overloading: o Operator overloading is done by defining a special function using the operator keyword followed by the operator symbol, for example: operator+, operator==, etc. o Overloaded operators can be implemented as either member functions or friend functions. 3. Operator Overloading with Member Functions vs. Friend Functions: o Member functions: The left operand must be an object of the class. For example, to overload + as a member function, you might write:
  • 2. SOMESH KUMAR DEWANGAN DEPARTMENT OF CSE 2 SHRI SHANKARACHARYA TECHNICAL CAMPUS Complex operator+(const Complex& other) const; o Friend functions: These can be used if the left operand is not an object of the class (e.g., a built-in type). Friend functions allow more flexibility in operator overloading. 4. Overloading Unary and Binary Operators: o Unary Operators: Operators like +, -, ++, and -- that operate on a single operand can be overloaded with one argument (if defined outside the class) or no arguments (if defined inside the class). o Binary Operators: Operators like +, -, *, /, and == that operate on two operands can be overloaded with two arguments (if defined outside the class) or one argument (if defined inside the class). 5. Rules and Limitations: o Precedence and Associativity: Overloading does not change the precedence or associativity of operators. o Operator Overloading Does Not Alter Default Behavior: You cannot create new operators or change the fundamental behavior of operators, such as the number of operands. o Return Types: The return type of an overloaded operator function should match the operation it represents. For example, an overloaded + operator usually returns a new object of the same type as the class. Overloading Various Operators Overloading the + Operator for a Complex Number Class The + operator is overloaded to add two complex numbers by adding their real and imaginary parts separately. #include <iostream> using namespace std; class Complex { double real, imag; public: Complex(double r = 0, double i = 0) : real(r), imag(i) {}
  • 3. SOMESH KUMAR DEWANGAN DEPARTMENT OF CSE 3 SHRI SHANKARACHARYA TECHNICAL CAMPUS // Overload the '+' operator Complex operator+(const Complex& other) const { return Complex(real + other.real, imag + other.imag); } void display() const { cout << real << " + " << imag << "i" << endl; } }; int main() { Complex c1(3.5, 2.5), c2(1.5, 4.0); Complex c3 = c1 + c2; // Uses overloaded '+' operator c3.display(); // Output: 5 + 6.5i } the + operator is overloaded to add the real and imag parts of Complex numbers. This makes adding complex numbers as intuitive as adding primitive types. Overloading the - Operator for a Vector Class Here, we overload the - operator to subtract two vectors (each with x, y, and z components). #include <iostream> using namespace std; class Vector { double x, y, z; public: Vector(double x_val = 0, double y_val = 0, double z_val = 0) : x(x_val), y(y_val), z(z_val) {} // Overload the '-' operator Vector operator-(const Vector& other) const {
  • 4. SOMESH KUMAR DEWANGAN DEPARTMENT OF CSE 4 SHRI SHANKARACHARYA TECHNICAL CAMPUS return Vector(x - other.x, y - other.y, z - other.z); } void display() const { cout << "Vector(" << x << ", " << y << ", " << z << ")" << endl; } }; int main() { Vector v1(5.0, 3.0, 2.0), v2(1.0, 1.5, 0.5); Vector v3 = v1 - v2; // Uses overloaded '-' operator v3.display(); // Output: Vector(4, 1.5, 1.5) } the - operator is overloaded to perform vector subtraction, allowing for intuitive vector manipulation. Overloading the == Operator for a Distance Class The == operator can be overloaded to compare two Distance objects by checking if both their feet and inches values are equal. #include <iostream> using namespace std; class Distance { int feet; double inches; public: Distance(int f = 0, double i = 0.0) : feet(f), inches(i) {} // Overload the '==' operator bool operator==(const Distance& other) const { return (feet == other.feet && inches == other.inches); }
  • 5. SOMESH KUMAR DEWANGAN DEPARTMENT OF CSE 5 SHRI SHANKARACHARYA TECHNICAL CAMPUS void display() const { cout << feet << " feet " << inches << " inches" << endl; } }; int main() { Distance d1(5, 9.5), d2(5, 9.5), d3(6, 4.0); if (d1 == d2) { cout << "d1 is equal to d2" << endl; } if (!(d1 == d3)) { cout << "d1 is not equal to d3" << endl; } } the == operator to compare if two Distance objects are equal, enhancing readability when comparing complex data types. Overloading the << (Insertion) Operator for Outputting Objects The << operator is typically used for outputting data to the console. We can overload it to print the contents of a Point class object directly. #include <iostream> using namespace std; class Point { int x, y; public: Point(int x_val = 0, int y_val = 0) : x(x_val), y(y_val) {} // Overload the '<<' operator friend ostream& operator<<(ostream& out, const Point& p) { out << "(" << p.x << ", " << p.y << ")";
  • 6. SOMESH KUMAR DEWANGAN DEPARTMENT OF CSE 6 SHRI SHANKARACHARYA TECHNICAL CAMPUS return out; } }; int main() { Point p1(3, 4), p2(5, 7); cout << "Point p1: " << p1 << endl; // Uses overloaded '<<' operator cout << "Point p2: " << p2 << endl; } By overloading the << operator, we can print Point objects in a more readable format, making it simpler to debug and display information. Overloading the [] Operator for a Custom Array Class The [] operator can be overloaded to provide array-like access to elements within a custom array class. cpp Copy code #include <iostream> using namespace std; class IntArray { int arr[5]; public: IntArray() { for (int i = 0; i < 5; ++i) arr[i] = 0; } // Overload the '[]' operator int& operator[](int index) { if (index >= 0 && index < 5)
  • 7. SOMESH KUMAR DEWANGAN DEPARTMENT OF CSE 7 SHRI SHANKARACHARYA TECHNICAL CAMPUS return arr[index]; else { cout << "Index out of bounds" << endl; exit(1); } } void display() const { for (int i = 0; i < 5; ++i) cout << arr[i] << " "; cout << endl; } }; int main() { IntArray array; array[0] = 10; // Uses overloaded '[]' operator array[1] = 20; array.display(); // Output: 10 20 0 0 0 } the [] operator is overloaded to access and modify elements of a custom array class, giving it array-like behavior and improving code readability. Overloading the ++ Operator for Incrementing The ++ operator can be overloaded to increment values, similar to its behavior with built-in types. #include <iostream> using namespace std; class Counter { int value; public: Counter(int v = 0) : value(v) {}
  • 8. SOMESH KUMAR DEWANGAN DEPARTMENT OF CSE 8 SHRI SHANKARACHARYA TECHNICAL CAMPUS // Overload the '++' operator (prefix) Counter& operator++() { ++value; return *this; } // Overload the '++' operator (postfix) Counter operator++(int) { Counter temp = *this; ++value; return temp; } void display() const { cout << "Counter value: " << value << endl; } }; int main() { Counter c(5); ++c; // Uses overloaded prefix '++' c.display(); // Output: Counter value: 6 c++; // Uses overloaded postfix '++' c.display(); // Output: Counter value: 7 } Type Conversion: Type conversion in C++ refers to converting one data type into another. This can involve both basic types (e.g., int, float) and user-defined types (e.g., classes). There are different types of conversions in C++:
  • 9. SOMESH KUMAR DEWANGAN DEPARTMENT OF CSE 9 SHRI SHANKARACHARYA TECHNICAL CAMPUS 1. Implicit Conversion (Automatic Conversion): Performed automatically by the compiler. For instance, when you assign an int to a float, the compiler automatically converts it. 2. Explicit Conversion (Casting): When conversions need to be made explicitly, as in static_cast, reinterpret_cast, const_cast, or dynamic_cast. 3. User-Defined Conversion: These are conversions defined by the programmer within a class, allowing objects of that class to be converted to and from other types. User-Defined Type Conversion C++ supports user-defined type conversions to make class objects behave like built-in types in certain situations. These conversions can be classified into: 1. Basic Type to Class Type Conversion: Converting a basic data type (like int, float, etc.) to a user-defined class type. 2. Class Type to Basic Type Conversion: Converting an object of a class type to a basic data type. 3. Class Type to Another Class Type Conversion: Converting an object of one class to an object of another class. 1. Basic Type to Class Type Conversion This is achieved by creating a constructor in the class that takes the basic type as a parameter. The compiler will use this constructor to convert the basic type to the class type. #include <iostream> using namespace std; class Distance { int feet; double inches; public: // Constructor that takes a single int parameter to convert from basic type to class type Distance(int totalInches) { feet = totalInches / 12; inches = totalInches % 12; } void display() const { cout << feet << " feet " << inches << " inches" << endl; } };
  • 10. SOMESH KUMAR DEWANGAN DEPARTMENT OF CSE 10 SHRI SHANKARACHARYA TECHNICAL CAMPUS int main() { Distance d = 37; // 37 inches automatically converts to Distance object d.display(); // Output: 3 feet 1 inches } Here, the constructor Distance(int totalInches) allows int to be automatically converted to a Distance object. When 37 is assigned to d, this constructor is invoked to convert it into a Distance instance. 2. Class Type to Basic Type Conversion For this conversion, you define a conversion operator in the class. The operator keyword is used to define the type to which the class object should be converted. #include <iostream> using namespace std; class Distance { int feet; double inches; public: Distance(int f, double i) : feet(f), inches(i) {} // Conversion operator to convert Distance to int operator int() const { return feet * 12 + inches; // Converts Distance object to total inches } }; int main() { Distance d(3, 4.5); int inches = d; // Converts Distance object to int cout << "Distance in inches: " << inches << endl; // Output: Distance in inches: 40 } operator int() allows the Distance object d to be converted to int. When assigned to inches, the compiler uses this conversion operator to obtain the equivalent integer. 3. Class Type to Another Class Type Conversion To convert an object from one class to another, you can either define a conversion constructor in the destination class or define a conversion operator in the source class.
  • 11. SOMESH KUMAR DEWANGAN DEPARTMENT OF CSE 11 SHRI SHANKARACHARYA TECHNICAL CAMPUS
  • 12. SOMESH KUMAR DEWANGAN DEPARTMENT OF CSE 12 SHRI SHANKARACHARYA TECHNICAL CAMPUS Using Conversion Constructor in Destination Class #include <iostream> using namespace std; class Distance { int feet; double inches; public: Distance(int f, double i) : feet(f), inches(i) {} int getFeet() const { return feet; } double getInches() const { return inches; } }; class MetricDistance { double meters; public: // Conversion constructor that takes a Distance object MetricDistance(const Distance& d) { meters = (d.getFeet() * 12 + d.getInches()) * 0.0254; // Convert to meters } void display() const { cout << meters << " meters" << endl; } }; int main() { Distance d(3, 3.5); MetricDistance md = d; // Converts Distance to MetricDistance using conversion constructor md.display(); // Output: 1.0049 meters }
  • 13. SOMESH KUMAR DEWANGAN DEPARTMENT OF CSE 13 SHRI SHANKARACHARYA TECHNICAL CAMPUS the MetricDistance class has a conversion constructor that takes a Distance object. This constructor converts Distance to MetricDistance by calculating the equivalent metric value in meters. Important Points to Note 1. Automatic Conversion Risks: Be cautious with user-defined conversions, as they may lead to ambiguous code or unexpected results when the compiler performs automatic conversions. 2. Explicit Keyword: C++11 introduced the explicit keyword for constructors to prevent unintended implicit conversions. When a constructor is marked explicit, it cannot be used for implicit conversions. Example with explicit Keyword class Distance { public: explicit Distance(int totalInches) { /*...*/ } }; Using explicit prevents the constructor from being used in implicit conversions, so Distance d = 37; would result in an error unless explicitly cast: Distance d = Distance(37);
  • 14. SOMESH KUMAR DEWANGAN DEPARTMENT OF CSE 14 SHRI SHANKARACHARYA TECHNICAL CAMPUS Inheritance Inheritance in C++ is a powerful object-oriented programming (OOP) feature that lets one class inherit the properties and behaviors of another class. This enables code reuse, modularity, and the formation of hierarchical class structures. Here’s a detailed explanation of inheritance concepts, including defining derived classes, forms of inheritance, handling ambiguity in multiple and multipath inheritance, virtual base classes, object slicing, function overriding, and constructor/destructor execution order. 1. Introduction to Inheritance Inheritance allows a derived class to acquire properties and behaviors (data members and methods) of a base class. This establishes an "is-a" relationship between classes, meaning a derived class can be considered a more specific version of a base class. For example: • A Car class can inherit from a Vehicle class, because a car "is-a" vehicle. • Inheritance enables the derived class to extend or modify the base class functionality. 2. Defining Derived Classes In C++, a derived class is created by using the following syntax: cpp Copy code class DerivedClass : access_specifier BaseClass { // Additional members and functions specific to DerivedClass }; • access_specifier (usually public, protected, or private) controls the inheritance visibility of base class members in the derived class. • The derived class inherits all the accessible members of the base class. Example: cpp Copy code #include <iostream> using namespace std;
  • 15. SOMESH KUMAR DEWANGAN DEPARTMENT OF CSE 15 SHRI SHANKARACHARYA TECHNICAL CAMPUS class Animal { public: void eat() { cout << "Eating..." << endl; } }; class Dog : public Animal { // Dog is derived from Animal public: void bark() { cout << "Barking..." << endl; } }; int main() { Dog d; d.eat(); // Inherited from Animal d.bark(); // Defined in Dog return 0; } 3. Forms of Inheritance There are several forms of inheritance in C++: • Single Inheritance: A derived class inherits from one base class. • Multiple Inheritance: A derived class inherits from more than one base class. • Multilevel Inheritance: A class derives from a class, which is also derived from another class, creating a chain. • Hierarchical Inheritance: Multiple classes inherit from a single base class. • Hybrid Inheritance: A combination of multiple and multilevel inheritance (can lead to ambiguity, resolved by virtual inheritance). In C++, inheritance can take several forms, each representing a different kind of relationship between base and derived classes. Here’s a breakdown of the different forms of inheritance, along with examples for clarity: 1. Single Inheritance
  • 16. SOMESH KUMAR DEWANGAN DEPARTMENT OF CSE 16 SHRI SHANKARACHARYA TECHNICAL CAMPUS Single inheritance is when a derived class inherits from only one base class. This is the simplest form of inheritance. Example: cpp Copy code #include <iostream> using namespace std; class Animal { public: void eat() { cout << "Eating..." << endl; } }; class Dog : public Animal { // Dog inherits from Animal public: void bark() { cout << "Barking..." << endl; } }; int main() { Dog d; d.eat(); // Inherited from Animal d.bark(); // Defined in Dog return 0; } In this example: • Dog is the derived class and Animal is the base class. • Dog inherits the eat() method from Animal and adds its own method, bark(). 2. Multiple Inheritance Multiple inheritance occurs when a derived class inherits from more than one base class. This allows the derived class to combine the functionalities of multiple base classes but
  • 17. SOMESH KUMAR DEWANGAN DEPARTMENT OF CSE 17 SHRI SHANKARACHARYA TECHNICAL CAMPUS can also introduce complexity due to potential conflicts (e.g., methods with the same name in different base classes). Example: cpp Copy code #include <iostream> using namespace std; class Animal { public: void eat() { cout << "Eating..." << endl; } }; class Mammal { public: void walk() { cout << "Walking..." << endl; } }; class Dog : public Animal, public Mammal { // Dog inherits from both Animal and Mammal public: void bark() { cout << "Barking..." << endl; } }; int main() { Dog d; d.eat(); // From Animal d.walk(); // From Mammal d.bark(); // Defined in Dog return 0; }
  • 18. SOMESH KUMAR DEWANGAN DEPARTMENT OF CSE 18 SHRI SHANKARACHARYA TECHNICAL CAMPUS In this example: • Dog inherits both eat() from Animal and walk() from Mammal. • This showcases how Dog can combine functionality from multiple base classes. 3. Multilevel Inheritance Multilevel inheritance occurs when a derived class serves as a base class for another class, creating a chain of inheritance. It establishes a hierarchy where each level builds upon the previous level. Example: cpp Copy code #include <iostream> using namespace std; class Animal { public: void eat() { cout << "Eating..." << endl; } }; class Dog : public Animal { public: void bark() { cout << "Barking..." << endl; } }; class Puppy : public Dog { // Puppy inherits from Dog, which inherits from Animal public: void weep() { cout << "Weeping..." << endl; } }; int main() { Puppy p;
  • 19. SOMESH KUMAR DEWANGAN DEPARTMENT OF CSE 19 SHRI SHANKARACHARYA TECHNICAL CAMPUS p.eat(); // Inherited from Animal p.bark(); // Inherited from Dog p.weep(); // Defined in Puppy return 0; } In this example: • Puppy inherits from Dog, which in turn inherits from Animal. • Puppy has access to eat() (from Animal), bark() (from Dog), and weep() (defined in Puppy), forming a chain of inheritance. 4. Hierarchical Inheritance Hierarchical inheritance occurs when multiple derived classes inherit from a single base class. This allows each derived class to share and possibly extend the properties and behaviors of the base class. Example: cpp Copy code #include <iostream> using namespace std; class Animal { public: void eat() { cout << "Eating..." << endl; } }; class Dog : public Animal { // Dog inherits from Animal public: void bark() { cout << "Barking..." << endl; } }; class Cat : public Animal { // Cat also inherits from Animal
  • 20. SOMESH KUMAR DEWANGAN DEPARTMENT OF CSE 20 SHRI SHANKARACHARYA TECHNICAL CAMPUS public: void meow() { cout << "Meowing..." << endl; } }; int main() { Dog d; Cat c; d.eat(); // Inherited from Animal d.bark(); // Defined in Dog c.eat(); // Inherited from Animal c.meow(); // Defined in Cat return 0; } In this example: • Both Dog and Cat are derived classes that inherit from the same base class, Animal. • Dog and Cat share the eat() method but have their own unique methods: bark() for Dog and meow() for Cat. 5. Hybrid Inheritance Hybrid inheritance is a combination of two or more of the above types of inheritance. It often involves both multiple and multilevel inheritance and can lead to the diamond problem. Diamond Problem The diamond problem occurs in hybrid inheritance when two derived classes inherit from the same base class, and a further class inherits from both of them. This creates ambiguity because the final derived class gets two copies of the base class members. Virtual inheritance solves this problem by ensuring only one instance of the base class exists. Example: cpp Copy code #include <iostream> using namespace std;
  • 21. SOMESH KUMAR DEWANGAN DEPARTMENT OF CSE 21 SHRI SHANKARACHARYA TECHNICAL CAMPUS class Animal { public: void eat() { cout << "Eating..." << endl; } }; class Mammal : virtual public Animal { }; // Virtual inheritance class Bird : virtual public Animal { }; // Virtual inheritance class Bat : public Mammal, public Bird { }; int main() { Bat b; b.eat(); // No ambiguity due to virtual inheritance return 0; } In this example: • Animal is the base class, with Mammal and Bird as derived classes using virtual inheritance. • Bat inherits from both Mammal and Bird, but Animal appears only once in Bat's hierarchy due to virtual inheritance, avoiding ambiguity. 4. Ambiguity in Multiple and Multipath Inheritance In multiple and multipath inheritance, ambiguity may arise if two or more parent classes have a member with the same name. This is common in complex hierarchies or "diamond-shaped" inheritance structures, where a base class is inherited multiple times through different paths. Example of Ambiguity: cpp Copy code #include <iostream>
  • 22. SOMESH KUMAR DEWANGAN DEPARTMENT OF CSE 22 SHRI SHANKARACHARYA TECHNICAL CAMPUS using namespace std; class A { public: void show() { cout << "A::show" << endl; } }; class B : public A { }; class C : public A { }; class D : public B, public C { }; int main() { D d; d.show(); // Error: ambiguous because of multiple inheritance from A return 0; } Here, D inherits show() from both B and C, leading to ambiguity. To resolve this, you can specify the path explicitly: cpp Copy code d.B::show(); Virtual Base Class (Resolving the Diamond Problem): To resolve ambiguity in complex inheritance structures, use virtual inheritance. By declaring the base class as a virtual base class, C++ ensures only one instance of the base class exists in the derived hierarchy. cpp Copy code class A { public: void show() { cout << "A::show" << endl; }
  • 23. SOMESH KUMAR DEWANGAN DEPARTMENT OF CSE 23 SHRI SHANKARACHARYA TECHNICAL CAMPUS }; class B : virtual public A { }; class C : virtual public A { }; class D : public B, public C { }; int main() { D d; d.show(); // No ambiguity due to virtual inheritance return 0; } 5. Object Slicing Object slicing occurs when an object of a derived class is assigned to an object of the base class, "slicing" off the derived part. cpp Copy code #include <iostream> using namespace std; class Base { public: int x; }; class Derived : public Base { public: int y; };
  • 24. SOMESH KUMAR DEWANGAN DEPARTMENT OF CSE 24 SHRI SHANKARACHARYA TECHNICAL CAMPUS int main() { Derived d; d.x = 1; d.y = 2; Base b = d; // Object slicing occurs here cout << b.x << endl; // Prints 1 // cout << b.y << endl; // Error: Base has no member y return 0; } Here, the y member of Derived is "sliced off" when d is assigned to b. To avoid object slicing, use pointers or references instead. 6. Overriding Member Functions In function overriding, a derived class redefines a function of the base class. To enable polymorphism, the base class function is declared as virtual, allowing the derived class version to be called. cpp Copy code #include <iostream> using namespace std; class Animal { public: virtual void sound() { cout << "Animal sound..." << endl; } }; class Dog : public Animal { public: void sound() override { cout << "Dog barks..." << endl; }
  • 25. SOMESH KUMAR DEWANGAN DEPARTMENT OF CSE 25 SHRI SHANKARACHARYA TECHNICAL CAMPUS }; int main() { Animal* a = new Dog(); a->sound(); // Calls Dog's sound() due to virtual function delete a; return 0; } 7. Order of Execution of Constructors and Destructors When an object of a derived class is created, the base class constructor is called first, followed by the derived class constructor. When destructing, the derived class destructor is called first, followed by the base class destructor. This ensures that the base part of the derived object is fully constructed and destructed. cpp Copy code #include <iostream> using namespace std; class Base { public: Base() { cout << "Base Constructor" << endl; } ~Base() { cout << "Base Destructor" << endl; } }; class Derived : public Base { public: Derived() { cout << "Derived Constructor" << endl; } ~Derived() { cout << "Derived Destructor" << endl; } };
  • 26. SOMESH KUMAR DEWANGAN DEPARTMENT OF CSE 26 SHRI SHANKARACHARYA TECHNICAL CAMPUS int main() { Derived d; return 0; } Output: Copy code Base Constructor Derived Constructor Derived Destructor Base Destructor In this example: • The Base constructor is called before the Derived constructor. • The Derived destructor is called before the Base destructor.