Unit – 3 Operator overloading and type conversion Inheritance
Concept of 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.
• Operator overloading is used to overload or redefines most of the operators available in C++.
• It is used to perform the operation on the user-defined data type.
• The advantage of Operators overloading is to perform different operations on the same
operand.
Operator that cannot be overloaded are as follows:
Scope operator (::)
Sizeof
member selector(.)
member pointer selector(*)
ternary operator(?:)
Syntax:
return_type class_name : : operator op(argument_list)
// body of the function.
• Where the return type is the type of value returned by the function.
• class_name is the name of the class.
• operator op is an operator function where op is the operator being overloaded, and the
operator is the keyword.
Program to overload the unary operator ++
#include <iostream.h>
#include <conio.h>
class Test
1
Unit – 3 Operator overloading and type conversion Inheritance
private:
int num;
public:
Test(): num(8){}
void operator ++() {
num = num+2;
void Print() {
cout<<"The Count is: "<<num;
};
int main()
clrscr();
Test tt;
++tt; // calling of a function "void operator ++()"
[Link]();
getch();
Operator Overloading in Unary Operators
Unary operators operate on only one operand. The increment operator ++ and decrement operator --
are examples of unary operators.
Example:
#include <iostream.h>
#include <conio.h>
2
Unit – 3 Operator overloading and type conversion Inheritance
class Count {
private:
int value;
public:
Count() : value(5) {}
void operator ++ () {
++value;
void display() {
cout << "Count: " << value << endl;
};
int main() {
clrscr();
Count count1;
++count1;
[Link]();
getch();
Operator Overloading in Binary Operators
Binary operators work on two operands.
For example,
result = num + 9;
Here, + is a binary operator that works on the operands num and 9.
When we overload the binary operator for user-defined types by using the code:
3
Unit – 3 Operator overloading and type conversion Inheritance
obj3 = obj1 + obj2;
The operator function is called using the obj1 object and obj2 is passed as an argument to the function.
There are multiple binary operators like +, -, *, /, etc., that can directly manipulate or overload the
object of a class.
Example:
#include <iostream.h>
#include <conio.h>
class Arith_num {
int x, y;
public:
void input() {
cout << " Enter the first number: ";
cin >> x;
void input2() {
cout << " Enter the second number: ";
cin >> y;
Arith_num operator + (Arith_num &ob) {
Arith_num A;
A.x = x + ob.y;
return (A); }
void print() {
cout << "The sum of two numbers is: " <<x;
4
Unit – 3 Operator overloading and type conversion Inheritance
};
int main () {
clrscr();
Arith_num x1, y1, res;
[Link]();
y1.input2();
res = x1 + y1;
[Link]();
getch();
Overloading of operators using friend Function
Operator overloading can be achieved in two ways -
• By an operator overloading by member function, or
• By an operator overloading non-member friend function.
• Friend function using operator overloading offers better flexibility to the class.
• When you overload a unary operator, you must pass one argument.
• When you overload a binary operator, you must pass two arguments.
• Friend function can access private members of a class directly.
Syntax:
friend return-type operator operator-symbol (Variable 1, Varibale2)
//Statements;
Example:
#include <iostream.h>
5
Unit – 3 Operator overloading and type conversion Inheritance
#include <conio.h>
class Coins {
private:
int a_coins;
public:
Coins(int coins):a_coins(coins) {}
friend Coins operator +(const Coins &c1, const Coins &c2);
int getCoins() const { return a_coins; }
};
Coins operator +(const Coins &c1, const Coins &c2) {
return Coins(c1.a_coins + c2.a_coins);
int main() {
clrscr();
Coins coins1(5);
Coins coins2(4);
Coins coinsSum(coins1 + coins2);
cout << "We have " << [Link]() << " coins.\n";
getch();
Manipulation of string using operators
C++ allows us to manipulate strings using the concept of operator overload.
For example, we may override the + operator to concatenate two strings.
C++ supports a wide range of functions that manipulate strings.
They are as follows:
6
Unit – 3 Operator overloading and type conversion Inheritance
strcpy(str1, str2): It copies the string str2 into string str1.
strcat(str1, str2): Concatenates string str2 onto the end of string str1.
strlen(str1): Returns the length of string str1.
strcmp(str1, str2): Returns 0 if str1 and str2 are the same; less than 0 if str1<str2, greater than 0 if
str1>str2.
Example:
#include <iostream.h>
#include <conio.h>
#include <string.h>
class AddString {
public:
char s1[25], s2[25];
AddString(char str1[], char str2[]) {
strcpy(this->s1, str1);
strcpy(this->s2, str2);
void operator +() {
cout << "\nConcatenation: " << strcat(s1, s2);
};
int main() {
clrscr();
char str1[] = "Sarvoday";
char str2[] = "College";
AddString a1(str1, str2);
7
Unit – 3 Operator overloading and type conversion Inheritance
+a1;
getch();
Rules for operator overloading
• Operator overloading is a type of static or compile-time polymorphism.
• C++ supports the compile-time polymorphism.
• The function overloading and the operator overloading are common examples of compile-time
polymorphism.
Let’s see the rules for the operator overloading.
1. Only built-in operators like (+, -, *, /, etc) can be overloaded.
2. We cannot overload all those operators that are not a part of C++ language like ‘$’.
3. We can’t change the behavior of the operators. The behavior of an operator is the number of
operands that the operator takes.
4. We can overload the unary operator as an only unary operator, and we cannot overload it as a
binary operator and similarly, We can overload binary operators as an only binary operator, and
we cannot overload it as a unary operator.
5. During the operator overloading, we cannot change the actual meaning of an operator. For
example, We cannot overload the plus(+) operator to subtract one value form the other value.
6. The precedence of the operators remains the same during operator overloading.
7. The operator overloading is not possible for built-in data types. At least one user-defined data
types must be there.
8. Some operators like assignment “=”, address “&” and comma “,” are by default overloaded.
Type conversions
C++ allows us to convert data of one type to that of another. This is known as type conversion.
There are two types of type conversion in C++.
Implicit Conversion
Explicit Conversion (also known as Type Casting)
8
Unit – 3 Operator overloading and type conversion Inheritance
Implicit Type Conversion
The type conversion that is done automatically done by the compiler is known as implicit type
conversion. This type of conversion is also known as automatic conversion.
Let us look at example of implicit type conversion.
Example:
#include <iostream.h>
#include <conio.h>
int main() {
clrscr();
int num_int;
double num_double = 9.99;
// implicit conversion
// assigning a double value to an int variable
num_int = num_double;
cout << "num_int = " << num_int << endl;
cout << "num_double = " << num_double << endl;
getch();
C++ Explicit Conversion
When the user manually changes data from one type to another, this is known as explicit conversion.
This type of conversion is also known as type casting.
There are major ways in which we can use explicit conversion in C++. They are:
C-style type casting (also known as cast notation)
Function notation (also known as old C++ style type casting)
Example:
#include <iostream.h>
9
Unit – 3 Operator overloading and type conversion Inheritance
#include <conio.h>
int main() {
clrscr();
// initializing a double variable
double num_double = 3.56;
cout << "num_double = " << num_double << endl;
// C-style conversion from double to int
int num_int1 = (int)num_double;
cout << "num_int1 = " << num_int1 << endl;
// function-style conversion from double to int
int num_int2 = int(num_double);
cout << "num_int2 = " << num_int2 << endl;
getch();
Defining derived classes
A derived class is defined by specifying it relationship with the base class.
The general form of defining a derived class is:
class derived-class-name : visibility-mode base-class-name
...
... //members of derived class
...
};
where, class is the required keyword,
derived-class-name is the name given to the derived class,
10
Unit – 3 Operator overloading and type conversion Inheritance
base-class-name is the name given to the base class,
: (colon) indicates that the derived-class-name is derived from the base-class-name,
visibility-mode is optional and, if present, may be either private or public.
Examples:
class ABC : private XYZ //private derivation
members of ABC
};
class ABC : public XYZ //public derivation
members of ABC
};
class ABC : XYZ //private derivation by default
members of ABC
};
When a base class is privately inherited by a derived class, ‘public members’ of the base class becomes
private members of the derived class and therefore the public members of the base class can only be
accessed by the member functions of the of the derived class. They are inaccessible to the objects of the
derived class.
Remember, a public member of the class can be accessed by its own objects by using the dot operator.
The result is that no member of the base class is accessible to the objects of the derived class in case of
private derivation.
On the other hand, when the base class is publicly inherited, ‘public members’ of the base class
becomes ‘public members’ of the derived class and therefore they are accessible to the objects of the
derived class.
Types of inheritance (Single, Multiple, Multi-level, Hierarchical, Hybrid)
Single Inheritance
11
Unit – 3 Operator overloading and type conversion Inheritance
The single inheritance can be used in such a way that one derived class inherits from only one base class.
And it is also known as the simplest form of inheritance.
Syntax:
class subclass_name : visibility_mode base_classname
//body of subclass
};
Example:
#include<iostream.h>
#include<conio.h>
class Vehicle {
public:
Vehicle() {
cout << "This is a Vehicle" << endl;
12
Unit – 3 Operator overloading and type conversion Inheritance
};
class Car: public Vehicle {
};
int main() {
clrscr();
//creating object of sub class will invoke the constructor of base classes
Car obj;
getch();
Multiple Inheritance
Multiple inheritance is the process of deriving a new class that inherits the attributes from two or more
classes.
Syntax:
class D : visibility B-1, visibility B-2, visibility B-n
// Body of the class;
13
Unit – 3 Operator overloading and type conversion Inheritance
Example:
#include<iostream.h>
#include<conio.h>
class A {
protected:
int a;
public:
void get_a(int n) {
a=n;
};
class B {
protected:
int b;
public:
void get_b(int n) {
b=n;
};
class C : public A, public B {
public:
void display() {
cout << "The value of a is : " << a << endl;
cout << "The value of b is : " << b << endl;
cout << "Addition of a and b is : " << a+b;
14
Unit – 3 Operator overloading and type conversion Inheritance
};
int main() {
clrscr();
C obj;
obj.get_a(10);
obj.get_b(20);
[Link]();
getch();
Multilevel Inheritance
When one class inherits another class which is further inherited by another class, it is known as multi
level inheritance in C++. Inheritance is transitive so the last derived class acquires all the members of all
its base classes.
Syntax:
class A {
... .. ...
};
class B: public A {
... .. ...
};
class C: public B {
... ... ...
};
15
Unit – 3 Operator overloading and type conversion Inheritance
Example:
#include <iostream.h>
#include <conio.h>
class Animal {
public:
Animal() {
cout<<"This is a Animal.";
};
class fourLegs : public Animal {
public:
fourLegs() {
16
Unit – 3 Operator overloading and type conversion Inheritance
cout << "Objects with 4 legs are Animals.";
};
class Cow : public fourLegs {
public:
Cow() {
cout<<"Cow has 4 Legs.";
};
int main() {
clrscr();
Cow obj;
getch();
Hierarchical Inheritance
Hierarchical inheritance is defined as the process of deriving more than one class from a base class.
Syntax:
class A {
// body of the class A.
class B : public A {
// body of class B.
class C : public A {
// body of class C.
17
Unit – 3 Operator overloading and type conversion Inheritance
class D : public A {
// body of class D.
Example:
#include<iostream.h>
#include<conio.h>
class Animal {
public:
Animal(){
cout<<"Animals Can Run.“ << endl;
};
class Dog : public Animal {
};
class Cat : public Animal {
18
Unit – 3 Operator overloading and type conversion Inheritance
};
int main(){
clrscr();
Cat obj1;
Dog obj2;
getch();
Hybrid Inheritance
Hybrid inheritance is a combination of more than one type of inheritance (Combining Hierarchical
inheritance and Multiple Inheritance.).
For example:- A child and parent class relationship that follows multiple and hierarchical inheritance
both can be called hybrid inheritance.
Example:
#include<iostream.h>
19
Unit – 3 Operator overloading and type conversion Inheritance
#include<conio.h>
class A {
protected:
int a;
public:
void get_a() {
cout << "Enter the value of 'a' : " << endl;
cin>>a; }
};
class B : public A {
protected:
int b;
public:
void get_b() {
cout << "Enter the value of 'b' : " << endl;
cin>>b; }
};
class C {
protected:
int c;
public:
void get_c() {
cout << "Enter the value of c is : " << endl;
cin>>c;
20
Unit – 3 Operator overloading and type conversion Inheritance
};
class D : public B, public C {
protected:
int d;
public:
void mul() {
get_a();
get_b();
get_c();
cout << "Multiplication of a,b,c is : " <<a*b*c << endl;
};
int main() {
clrscr();
D d;
[Link]();
getch();
Virtual Base Class
Base classes are the classes from which other classes are derived. The derived(child) classes have access
to the variables and methods/functions of a base(parent) class. The entire structure is known as the
inheritance hierarchy.
Let us consider the image, Class A is the parent class, and Classes B and C are the derived classes from
Class A. Class B and Class C have all the properties of Class A.
Next, Class D inherits Class B and Class C. With our knowledge,Class D will get all the properties from
Class B and C, which also has Class A properties. When we try to access Class A’s properties through D,
there will be an error because Class D will get Class A’s properties twice, and the compiler can’t decide
what to output.
21
Unit – 3 Operator overloading and type conversion Inheritance
Virtual Class is defined by writing a keyword “virtual” in the derived classes, allowing only one copy of
data to be copied to Class B and Class C (referring to the above example). It prevents multiple instances
of a class appearing as a parent class in the inheritance hierarchy when multiple inheritances are used.
To prevent the error and let the compiler work efficiently, we’ve to use a virtual base class when
multiple inheritances occur. It saves space and avoids error.
When a class is specified as a virtual base class, it prevents duplication of its data members. Only one
copy of its data members is shared by all the base classes that use the virtual base class.
If a virtual base class is not used, all the derived classes will get duplicated data members. In this case,
the compiler cannot decide which one to execute.
Example:
#include <iostream.h>
#include <conio.h>
class A {
public:
A() {
cout << "Constructor A\n";
22
Unit – 3 Operator overloading and type conversion Inheritance
void display() {
cout << "Hello form Class A \n";
} };
class B: public virtual A {
};
class C: public virtual A {
};
class D: public B, public C {
};
int main() {
clrscr();
D object;
[Link]();
getch();
Abstract class
The C++ interfaces are implemented using abstract classes. Abstraction is a concept of keeping
implementation details separate from associated data.
A class is made abstract by declaring at least one of its functions as pure virtual function. A pure virtual
function is specified by placing "= 0" in its declaration as follows −
class Box {
public:
// pure virtual function
virtual double getVolume() = 0;
private:
double length; // Length of a box
23
Unit – 3 Operator overloading and type conversion Inheritance
double height; // Height of a box
};
The purpose of an abstract class is to provide an appropriate base class from which other classes can
inherit. Abstract classes cannot be used to instantiate objects and serves only as an interface.
Example:
#include<iostream.h>
#include<conio.h>
class Shape {
public:
// pure virtual function providing interface framework.
virtual int getArea() = 0;
void setWidth(int w) {
width = w;
void setHeight(int h) {
height = h;
protected:
int width;
int height;
};
class Rectangle: public Shape {
public:
int getArea() {
return (width * height);
24
Unit – 3 Operator overloading and type conversion Inheritance
};
class Triangle: public Shape {
public:
int getArea() {
return (width * height)/2;
};
void main() {
clrscr();
Rectangle Rect;
Triangle Tri;
[Link](5);
[Link](7);
cout << "Total Rectangle area: " << [Link]() << endl;
[Link](5);
[Link](7);
cout << "Total Triangle area: " << [Link]() << endl;
getch();
Constructors in derived class
Whenever we create an object of a class, the default constructor of that class is invoked automatically to
initialize the members of the class.
If we inherit a class from another class and create an object of the derived class, it is clear that the
default constructor of the derived class will be invoked but before that the default constructor of all of
the base classes will be invoke.
Example1:
25
Unit – 3 Operator overloading and type conversion Inheritance
#include <iostream.h>
#include <conio.h>
class Parent {
public:
Parent() {
cout << "Inside base class" << endl;
};
class Child : public Parent {
public:
Child() {
cout << "Inside sub class" << endl;
};
int main() {
clrscr();
Child obj;
getch();
Example2:
#include <iostream.h>
#include <conio.h>
class Parent1 {
public:
Parent1() {
26
Unit – 3 Operator overloading and type conversion Inheritance
cout << "Inside first base class" << endl;
};
class Parent2 {
public:
Parent2() {
cout << "Inside second base class" << endl;
};
class Child : public Parent1, public Parent2 {
public:
Child() {
cout << "Inside child class" << endl;
};
int main() {
clrscr();
Child obj1;
getch();
C++ program to the sequence of execution of constructor and destructor inheritance
#include <iostream.h>
#include <conio.h>
class parent {
public:
27
Unit – 3 Operator overloading and type conversion Inheritance
parent() {
cout << "Parent class Constructor\n";
~parent() {
cout << "Parent class Destructor\n";
};
class child : public parent {
public:
child() {
cout << "Child class Constructor\n";
~child() {
cout << "Child class Destructor\n";
};
int main() {
clrscr();
child c;
getch();
Containership
In C++, it is possible to create an object in one class into another class, and that object is a member of
another class. This relationship is known as a containership.
The class containing the object in one class into another is known as the container class. The object that
is present in the container class is known as a contained object.
28
Unit – 3 Operator overloading and type conversion Inheritance
Syntax of Containership:
class One {
};
// Container class
class Two {
// creating object of One
One O;
};
Example:
#include <iostream.h>
#include <conio.h>
class first {
public:
first(){
cout << "Hello from first class\n";
};
//container class
class second {
first f;
public:
second(){
cout << "Hello from second class\n";
};
29
Unit – 3 Operator overloading and type conversion Inheritance
int main(){
clrscr();
second s;
getch();
Inheritance V/s Containership
Containership: When an object of one class is created into another class then that object will be a
member of that class, this type of relationship between the classes is known as containership.
The class which contains the object and members of another class in this kind of relationship is called a
container class and the object that is part of another object is called a contained object.
Inheritance: Inheritance is a type of process in which a new class is derived from an old class.
The reusability of the code is supported by inheritance.
With the help of inheritance, some additional features can be added to a new class. Once a class is
written, it is not possible to write it again.
30