Unit 3
Unit 3
SYLLABUS
UNIT III
Operator Overloading: Overloading unary, binary operators –Overloading Friend functions –type
conversion – Inheritance: Types of Inheritance – Single, Multilevel, Multiple,
Hierarchal, Hybrid, Multi path inheritance – Virtual base Classes – Abstract Classes.
Operator Overloading
C++ has the ability to provide the operators with a special meaning for a data type, this ability
is known as operator overloading. Operator overloading is a compile-time polymorphism. For
example, we can overload an operator ‘+’ in a class like String so that we can concatenate two
strings by just using +. Other example classes where arithmetic operators may be overloaded
are Complex Numbers, Fractional Numbers, Big integers, etc.
To conduct mathematical and logical operations on numerical quantities, C++ includes a wide
variety of operators. The unary operators are one such extensively used operator. Unary
Operators work on the operations carried out on just one operand. Unary operators do not utilize
two operands to calculate the result as binary operators do.
A single operand/variable is used with the unary operator to determine the new value of that
variable. Unary operators are used with the operand in either the prefix or postfix position. Unar y
operators come in various forms and have right-to-left associativity and equal precedence.
#include <iostream>
class Complex {
private:
int real, img;
public: Complex() {
real = 0;
img = 0;
}
Complex(int r, int i) {
real = r;
img = i;
}
}
There are two ways for unary operation overloading in C++, i.e.,
Let's see both methods below using the Complex class defined above.
B. Overload Unary Minus (-) Operator using class Member function
C++ Program:
#include <iostream>
class Complex {
private: int real,
img;
public: Complex() {
real = 0;
img = 0;
}
Complex(int r, int i) {
real = r;
img = i;
}
int main() {
// Instantiating a Complex object c1 with values.
Complex c1(-3, 4);
return 0;
}
Try it yourself
Output:
c1 = -3 + i4
c2 = 3 - i4
Explanation:
In the above C++ program, we have overloaded a minus (-) unary operator to work with
the Complex class objects.
We can't simply use the minus (-) operator with the Complex class object. It will give a
compilation error until we have defined the minus (-) operator w.r.t to the Complex class
objects.
We have provided a minus (-) operator overloaded definition in the Complex class. It is
invoked when we have used the unary minus(-) operator in the main() function with
the c2 object.
BINARY
Here, ‘+’ is the addition operator. ‘a’ and ‘b’ are the operands that are being ‘added’.
Arithmetic Operators
Relational Operators
Logical Operators
Bitwise Operators
Assignment Operators
Ternary or Conditional Operators
1) Arithmetic Operators
These operators are used to perform arithmetic or mathematical operations on the operands. For
example, ‘+’ is used for addition, ‘-‘ is used for subtraction ‘*’ is used for multiplication, etc.
int a = 5;
Increment Increases the integer value of the variable
++ a++; // returns
Operator by one
6
Name Symbol Description Example
int a = 5;
Decrement Decreases the integer value of the variable
— a–; // returns
Operator by one
4
Example:
the description
Output
a++ is 10
++a is 12
b-- is 15
--b is 13
int a = 3, b = 6;
Addition + Adds two operands
int c = a+b; // c =
Name Symbol Description Example
int a = 9, b = 6;
Subtraction – Subtracts second operand from the first int c = a-b; // c =
3
int a = 3, b = 6;
Multiplication * Multiplies two operands int c = a*b; // c =
18
int a = 8, b = 6;
Modulo Returns the remainder an integer
% int c = a%b; // c =
Operation division
2
Note: The Modulo operator(%) operator should only be used with integers.
Example:
C++
int main()
int a = 8, b = 3;
// Addition operator
// Subtraction operator
// Multiplication operator
// Modulo operator
return 0;
Output
a + b = 11
a-b=5
a * b = 24
a/b=2
a%b=2
These operators are used for the comparison of the values of two operands. For example, ‘>’
checks if one operand is greater than the other operand or not, etc. The result returns a Boolean
value, i.e., true or false.
int a = 3, b
= 6;
// returns
false
int a = 3, b
= 6;
Checks if first operand is greater than the
Greater Than > a>b;
second operand
// returns
false
int a = 3, b
= 6;
Greater Than or Checks if first operand is greater than or
>= a>=b;
Equal To equal to the second operand
// returns
false
Name Symbol Description Example
int a = 3, b
= 6;
Checks if first operand is lesser than the
Less Than < a<b;
second operand
// returns
true
int a = 3, b
= 6;
Less Than or Checks if first operand is lesser than or equal
<= a<=b;
Equal To to the second operand
// returns
true
int a = 3, b
= 6;
// returns
true
Example:
C++
int main()
int a = 6, b = 4;
// Equal to operator
// true
return 0;
Output
a == b is 0
a > b is 1
a >= b is 1
a < b is 0
a <= b is 0
a != b is 1
3) Logical Operators
These operators are used to combine two or more conditions or constraints or to complement the
evaluation of the original condition in consideration. The result returns a Boolean value,
i.e., true or false.
int a = 3, b =
6;
Logical Returns true only if all the operands are true or
&&
AND non-zero a&&b;
// returns true
int a = 3, b =
6;
Returns true if either of the operands is true or
Logical OR ||
non-zero a||b;
// returns true
Logical int a = 3;
! Returns true if the operand is false or zero
NOT !a;
Name Symbol Description Example
// returns
false
Example:
C++
#include <iostream>
int main()
int a = 6, b = 4;
return 0;
Output
a && b is 1
a ! b is 1
!b is 0
int a = 2, b =
Copies a bit to the evaluated result if it exists 3;
Binary AND &
in both operands (a & b);
//returns 2
int a = 2, b =
Copies a bit to the evaluated result if it exists 3;
Binary OR |
in any of the operand (a | b);
//returns 3
int a = 2, b =
Copies the bit to the evaluated result if it is 3;
Binary XOR ^
present in either of the operands but not both (a ^ b);
//returns 1
int a = 2, b =
Shifts the value to left by the number of bits 3;
Left Shift <<
specified by the right operand. (a << 1);
//returns 4
Right Shift >> Shifts the value to right by the number of bits int a = 2, b =
Name Symbol Description Example
(a >> 1);
//returns 1
int b = 3;
One’s
~ Changes binary digits 1 to 0 and 0 to 1 (~b);
Complement
//returns -4
Note: Only char and int data types can be used with Bitwise Operators.
Example:
C++
#include <iostream>
int main()
int a = 6, b = 4;
// Binary AND operator
// Binary OR operator
return 0;
Output
a & b is 4
a | b is 6
a ^ b is 2
a<<1 is 12
a>>1 is 3
~(a) is -7
5) Assignment Operators
These operators are used to assign value to a variable. The left side operand of the assignment
operator is a variable and the right side operand of the assignment operator is a value. The value
on the right side must be of the same data type as the variable on the left side otherwise the
compiler will raise an error.
int a =
Assignment Assigns the value on the right to the variable
= 2;
Operator on the left
// a = 2
int a = 2,
Add and First adds the current value of the variable on
b = 4;
Assignment += left to the value on the right and then assigns
Operator the result to the variable on the left a+=b; //
a=6
int a = 2,
Subtract and First subtracts the value on the right from the
-= b = 4;
Assignment current value of the variable on left and then
Operator assign the result to the variable on the left a-=b; //
a = -2
int a = 2,
Multiply and First multiplies the current value of the
b = 4;
Assignment *= variable on left to the value on the right and
Operator then assign the result to the variable on the left a*=b; //
a=8
int a = 4,
Divide and First divides the current value of the variable
/= b = 2;
Assignment on left by the value on the right and then
a /=b; //
Namemultiply Symbol Description Example
Example:
C++
#include <iostream>
int main()
int a = 6, b = 4;
// Assignment Operator
return 0;
Output
a=6
a += b is 10
a -= b is 6
a *= b is 24
a /= b is 6
The ternary operator ? determines the answer on the basis of the evaluation of Expression1. If it
is true, then Expression2 gets evaluated and is used as the answer for the expression.
If Expression1 is false, then Expression3 gets evaluated and is used as the answer for the
expression.
This operator takes three operands, therefore it is known as a Ternary Operator.
Example:
C++
#include <iostream>
int a = 3, b = 4;
// Conditional Operator
cout << "The greatest number is " << result << endl;
return 0;
Output
C) -> Operator: This operator is used to access the variables of classes or structures.
cout<<emp->first_name;
D) Cast Operator: This unary operator is used to convert one data type into another.
float a = 11.567;
E) Dot Operator(.): This operator is used to access members of structure variables or class
objects in C++.
cout<<emp.first_name;
F) & Operator: This is a pointer operator and is used to represent the memory address of an
operand.
G) * Operator: This is an Indirection Operator
C++
#include <iostream>
int a = 6;
int* b;
int c;
// & Operator
b = &a;
// * Operator
c = *b;
return 0;
}
Output
a=6
b = 0x7ffe8e8681bc
c=6
H) << Operator: It is called the insertion operator. It is used with cout to print the output.
I) >> Operator: It is called the extraction operator. It is used with cin to get the input.
int a;
cin>>a;
cout<<a;
* Dereference
6.
+= , -= Addition/subtraction assignment
*= , /= Multiplication/division assignment
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving
tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content
at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join
the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
20
Previous
Similar Reads
private:
int real;
int img;
public:
real = r;
img = i;
Complex temp;
return temp;
void Display()
};
int main()
C1.Display();
C2.Display();
Complex C3;
C3.Display();
}
Suppose we want to add two complex numbers i.e. C1 and C2,
C3 = C1 + C2;
It is possible for implicit conversions to lose information, signs can be lost (when
signed is implicitly converted to unsigned), and overflow can occur (when long long is
implicitly converted to float).
Explicit Type Conversion: This process is also called type casting and it is user-defined.
Here the user can typecast the result to make it of a particular data type.
In C++, it can be done by two ways:
Converting by assignment: This is done by explicitly defining the required type in front
of the expression in parenthesis. This can be also considered as forceful casting.
Conversion using Cast operator: A Cast operator is an unary operator which forces one
data type to be converted into another data type.
C++ supports four types of casting:
1. Static Cast
2. Dynamic Cast
3. Const Cast
4. Reinterpret Cast
Advantages of Type Conversion:
5. This is done to take advantage of certain features of type hierarchies or type
representations.
6. It helps to compute expressions containing variables of different data types.
Inheritance in C++
Inheritance is a feature or a process in which, new classes are created from the existing
classes. The new class created is called “derived class” or “child class” and the existing class
is known as the “base class” or “parent class”. The derived class now is said to be inherited
from the base class.
When we say derived class inherits the base class, it means, the derived class inherits all the
properties of the base class, without changing the properties of base class and may add new
features to its own. These new features in the derived class will not affect the base class. The
derived class is the specialized class for the base class.
Sub Class: The class that inherits properties from another class is called Subclass or
Derived Class.
Super Class: The class whose properties are inherited by a subclass is called Base Class
or Superclass.
Why and when to use inheritance?
Consider a group of vehicles. You need to create classes for Bus, Car, and Truck. The
methods fuelAmount(), capacity(), applyBrakes() will be the same for all three classes. If we
create these classes avoiding inheritance then we have to write all of these functions in each
of the three classes as shown below figure:
You can clearly see that the above process results in duplication of the same code 3 times.
This increases the chances of error and data redundancy. To avoid this type of situation,
inheritance is used. If we create a class Vehicle and write these three functions in it and
inherit the rest of the classes from the vehicle class, then we can simply avoid the duplication
of data and increase re-usability. Look at the below diagram in which the three classes are
inherited from vehicle class:
Using inheritance, we have to write the functions only one time instead of three times as we
have inherited the rest of the three classes from the base class (Vehicle).
Implementing inheritance in C++: For creating a sub-class that is inherited from the base
class we have to follow the below syntax.
Derived Classes: A Derived class is defined as the class derived from the base class.
Syntax:
class <derived_class_name> : <access-specifier> <base_class_name>
{
//body
Example:
1. class ABC : private XYZ //private derivation
{ }
2. class ABC : public XYZ //public derivation
{ }
3. class ABC : protected XYZ //protected derivation
{ }
4. class ABC: XYZ //private derivation by default
{ }
Types Of Inheritance:-
1. Single inheritance
2. Multilevel inheritance
3. Multiple inheritance
4. Hierarchical inheritance
5. Hybrid inheritance
1. Single Inheritance: In single inheritance, a class is allowed to inherit from only one class.
i.e. one subclass is inherited by one base class only.
Syntax:
class subclass_name : access_mode base_class
// body of subclass
};
OR
class A
... .. ...
};
class B: public A
... .. ...
};
Multiple Inheritance: Multiple Inheritance is a feature of C++ where a class can inherit
from more than one class. i.e one subclass is inherited from more than one base class.
3. Multilevel Inheritance: In this type of inheritance, a derived class is created from another
derived class.
Syntax:-
class C
... .. ...
};
class B:public C
... .. ...
};
class A: public B
};
4. Hierarchical Inheritance: In this type of inheritance, more than one subclass is inherited
from a single base class. i.e. more than one derived class is created from a single base class.
Syntax:-
class A
class B : public A
// body of class B.
class C : public A
// body of class C.
class D : public A
{
// body of class D.
Need for Virtual Base Classes: Consider the situation where we have one class A . This
class 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.
As we can see from the figure that data members/function of class A are inherited twice to
class D. One through class B and second through class C. When any data / function member
of class A is accessed by an object of class D, ambiguity arises as to which data/function
member would be called? One inherited through B or the other inherited through C. This
confuses compiler and it displays error.
Abstract classes
An abstract class is a class that is designed to be specifically used as a base class. An
abstract class contains at least one pure virtual function. You declare a pure virtual
function by using a pure specifier (= 0) in the declaration of a virtual member function in
the class declaration.