You are on page 1of 18

Operator Overloading

The mechanism of giving a special meaning for a data type to an operator is known as operator
overloading. The operator overloading is a compile time polymorphism.

The following operator cannot be overloaded:

(i) Class member access operator (. * )


(ii) Scope resolution operator (::)
(iii) Size operator (sizeof)
(iv) Conditional operator (? :)

Steps of operator overloading:

(i) First create a class that defines the data type that is to be used in the overloading operation
(ii) Declare the operator function operator op() in the public part of the class. It may be either a
member function or a friend function.
(iii) Define the operator function to implement the required operations

Rules for operator overloading:


(i) Only existing operators can be overloaded but new operator cannot be overloaded.
(ii) The overloaded operator must have at least one operand that is of user defined type.
(iii) We cannot change the basic meaning of an operator.
(iv) Overloaded operator follows the syntax rule of the original operator.
(v) Operator can be overloaded by means of friend function and member function.
(vi) Assignment operator (=), function calling operator (), subscripting operator ([]) cannot be
overloaded by friend function.
(vii) When unary operator overloaded by means of member function it does not take any explicit
argument and does not return the any value explicitly.
(viii) Unary operator overloading by friend function take one argument explicitly.
(ix) The left hand operand should be an object when the binary operator is overloaded by
member function.

Q1. Create a class consisting of an integer and floating point data members. Write member function to
read values to perform addition and to display values.

(i) Solve the problem using member function

#include <iostream.h>
class Number{
private:
int a;
float f;
public :
void input(){
cout<<”Enter an integer and a float value”;
cin>>i>>f;
}
Number operator+ (Number Y){
Number Z;
Z.i = i + Y.i;
Z.f = f+Y.f;
return Z;
}
void display(){
cout<<”i=”<<i<<”f=”<<f<<endl;
}
};

int main(){
Number A, B, C;
A.input();
B.input();

C = A+B; //C=A.operator+(B)

C.display();
return 0;
}

(ii) Solve the problem using friend function

#include <iostream.h>
class Number{
private:
int a;
float f;
public :
void input(){
cout<<”Enter an integer and a float value”;
cin>>i>>f;
}
friend Number operator+ (Number X, Number Y);
void display(){

cout<<”i=”<<i<<”f=”<<f<<endl;
}
};

Number operator+ (Number X, Number Y){


Number Z;

Z.i =X. i + Y.i;


Z.f = X. f+Y.f;
return Z;
}

int main(){
Number A, B, C;
A.input();
B.input();

C = A+B; //C=A.operator+(B)

C.display();
return 0;
}

Q3. Matrix addition using operator overloading when the matrix is dynamically allocated.

#include <iostream.h>
class Matrix{
private:
int **a;
int rs, cs;
public :
Matrix(){
rs=0;
cs=0;
}
Matrix(int r, int c){
rs=r;
cs=c;
for(int i=0; i<rs; i++){
a[i] = new int[cs];
}
}

void getdata(){
for(int i=0; i<rs;i++){
for(int j=0;j<cs;j++){
cin>>a[i][j];
}
}
}
Matrix operator+ (Matrix Y){
Matrix Z(rs, cs);
for(int i=0; i<rs;i++){
for(int j=0;j<cs;j++){
Z.a[i][j] = a[i][j] + Y.a[i][j];
}
}
return Z;
}

void display(){
for(int i=0; i<rs;i++){
for(int j=0;j<cs;j++){
cout<<a*i+*j+<<” ”;
}
cout<<endl;
}
}
};

int main(){
Matrix A(2,3), B(2,3), C(2,3);
A.getdata();
B.getdata();

C = A+B; //C=A.operator+(B)

C.display();
return 0;
}
This Pointer
‘this’ is a pointer in C++. It stores the address of the class instance which is called from the
member function that enables functions to access the correct object data members.

 We don’t need to define the ‘this’ pointer.


 ‘this’ pointer cannot be modified externally compiler define it.
 ‘this’ pointer can be returned.

Q1. Demonstration of this pointer to access the function argument has the same name with the class
data member.

#include <iostream.h>
class Number{
private: int a;
public :
Number(){
a=0;
}
Number(int a){
this  a=a;
}
void display(){
cout<<”a=”<<this  a<<endl;
}
};

int main(){
Number A(10), B(22);
A.display();
B.display();
return 0;
}
Q2. Use of “This” pointer in assignment operator (=) overloading

#include <iostream.h>
class Number{
private: int a;
public :
Number(){
a=0;
}
Number(int x){
a=x;
}
Number operator = (Number Y){
a=Y.a
return *this
}
void display(){
cout<<”a=”<<a<<endl;
}
};

int main(){
Number A(10), B;
B=A;
return 0;
}
Inheritance
Definition: It is a process of creating new class from one or more existing classes. The existing class is
known as base class and the newly created class is termed as child class.

• Inheritance is one of the most important and useful characteristics of object oriented
programming. (Do not write as a definition)

• Literal meaning: Adopting feature from newly created thing from the existing one.

Class A Base Class


Inheritance
Class B Derived Class

• Consider a group of vehicles. Examples: Bus, Car, Truck.

• For creating the class for each individual vehicles Bus, Car and Truck the same type of data and
method will be defined more than one time.

– Like: The methods fuelAmount(), capacity() will be same for all of the three classes.

• If we create these classes avoiding inheritance

Vehicle

fuelAmount()
capacity()

Bu Car Truc
s k

• Syntax for implementing inheritance: class subclass_name: visibility/access_mode


base_class_name()
Prog1:

#include <iostream>

using namespace std;

class Vehicle {

public:

int reg;

};

class Car : public Vehicle {

public: int id_c;

};

int main() {

Car obj1;

obj1.id_c = 7;

obj1.reg = 91;

cout << “Car id is " << obj1.id_c << endl;

cout << “Vehicle id is " << obj1.reg << endl;

return 0;

Mode of Inheritance:
• Public mode: If we derive a sub class from a public base class. Then the public member of the
base class will become public in the derived class and protected members of the base class will
become protected in derived class.

• Protected mode: If we derive a sub class from a Protected base class. Then both public member
and protected members of the base class will become protected in derived class.

• Private mode: If we derive a sub class from a Private base class. Then both public member and
protected members of the base class will become Private in derived class.
Base class member Type of Inheritance (Visibility Mode)
access specifier
Public Protected Private

Public Public Protected Private

Protected Protected Protected Private

Private Not accessible Not accessible Not accessible

prog2:

class A {
public: int x;
protected: int y;
private: int z;
};
class B : public A {
// x is public
// y is protected
// z is not accessible from B
};
class C : protected A {
// x is protected
// y is protected
// z is not accessible from C
};
class D : private A {
// x is private
// y is private
// z is not accessible from D
};

Types of Inheritance:
• Depending on the way the class is derived or how many base classes a class inherits, we have
the following types of inheritance:
(i) Single Inheritance
(ii) Multiple Inheritance
(iii) Multilevel Inheritance
(iv) Hierarchical Inheritance
(v) Hybrid Inheritance

(i) Single Inheritance:


• In single inheritance, a class is allowed to inherit from only one class. i.e. one sub class is
inherited by one base class only.
• Single inheritance declares as follows:
class subclassname : accessspecifier superclassname {
//class specific code;
};
Example-Prog1:
#include <iostream>
using namespace std;
class Vehicle {
public:
int reg;
};
class Car : public Vehicle {
public:
int id_c;
};
int main() {
Car obj1;
obj1.id_c = 7;
obj1.reg = 91;
cout << “Car id is " << obj1.id_c << endl;
cout << “Vehicle id is " << obj1.reg << endl;
return 0;
}

(ii) Multiple Inheritance:


 Multiple Inheritance is a feature of C++ where a class can inherit from more than one
classes. i.e one sub class is inherited from more than one base class.
 Here, the number of base classes will be separated by a comma (‘, ‘) and access mode for
every base class must be specified.
 Syntax: class subclass_name : access_mode base_class1, access_mode base_class2{
//body of subclass };
Base Class-2 Base Class-1
FourWheeler Vehicle
Inheritance
Car
Derived Class
Prog-2
#include <iostream>
using namespace std;
class Vehicle {// first base class
public:
Vehicle() {
cout << "This is a Vehicle" << endl;
}
};

class FourWheeler {// second base class


public:
FourWheeler() {
cout<<"This is a 4 wheeler Vehicle"<<endl;
}
};

// sub class derived from two base classes


class Car: public Vehicle, public FourWheeler {
public:
Car(){
cour<<“This is a car”<<endl;
}
};
// main function
int main() {
// creating object of sub class will
// invoke the constructor of base classes
Car obj;
return 0;
}
(iii) Multilevel Inheritance
 In this type of inheritance, a derived class is created from another derived class.
o Syntax: class subclass1 : accessspecifier superclass {//class specific code;};
o class subclass2 : accessspecifier subclass1 {//class specific code;};

Prog3:

#include <iostream>
using namespace std; Vehicle Base Class
class Vehicle {// first base class
public:
Vehicle() { Inheritance
cout << "This is a Vehicle" << endl;
}
}; FourWheeler Base Class
class FourWheeler: public Vechcle {// second base class
public:
FourWheeler() { Inheritance
cout <"This is a 4 wheeler Vehicle" <<endl;
}
};
Car Derived Class
// sub class derived from two base classes
class Car: public FourWheeler {
cout<<"Car has 4 Wheels"<< endl;
};
// main function
int main() {
Car obj;
return 0;
}
Note: Creating object of sub class will invoke the constructor of base classes.

(iv) Hierarchical Inheritance

Base Class-1

Vehicle

Derived Class-1 Derived Class-2


Base Class-2 TwoWheeler FourWheeler Base Class-3

Bike Cycle
Derived Class-3 Derived Class-4
 In this type of inheritance, more than one sub class is inherited from a single base class. i.e.
more than one derived class is created from a single base class.
o Syntax: class subclass_name : access_mode base_class1 {//body of subclass};

 Prog 4:
o #include <iostream>
using namespace std;
class Vehicle { // base class
public:
Vehicle() {
cout << "This is a Vehicle" << endl;
}
};
class TwoWheeler: public Vehicle{
TwoWheeler(){
cout<<“This is a two wheeler”<<endl;
}
};
class Bike: public TwoWheeler{
};
class Cycle: public TwoWheeler{
};

// second sub class


class FourWheeler: public Vehicle{
public:
FourWheeler(){
cout<<“This is a four wheeler”<<endl;
}
};
class Bus: public FourWheeler{
};
class Bus: public FourWheeler{
};
// main function
int main() {
Car obj1;
Bus obj2;
return 0;
}
(v) Hybrid (Virtual) Inheritance:
 Hybrid Inheritance is implemented by combining more than one type of inheritance. For
example: Combining Hierarchical inheritance and Multiple Inheritance.
 Syntax:
 class subclass_name : access_mode base_class1{//body of subclass };

Base Class-1 Base Class-2

SuperClass1 SuperClass2

Derived Class-1
Base Class-3
SubClass1 SubClass2
Derived Class-4

SubClass11 SubClass12
Derived Class-2 Derived Class-3

Prog-5

#include <iostream>
using namespace std;

class SuperClass1 {// base class


public:
Vehicle() {
cout << "This is First Super Class" << endl;
}
};
class SuperClass2 {//base class
public:
Fare() {
cout<<“This is second Super Class“<<endl;
}
};

//Hierarchical inheritance
class SubClass1: public SuperClass1 {
};
class SubClass11: public SubClass1 {
};
class SubClass12: public SubClass1 {
};
//Multiple inheritance
class SubClass2: public SuperClass1, public SuperClass2{
};
// main function
int main() {
SubClass11 obj11;
SubClass2 obj2;
return 0;
}

(vi) Multipath Inheritance:


a. A derived class with two base classes and these two base classes have one common
base class is called multipath inheritance.
b. An ambiguity can arise in this type of inheritance.

Base Class-1

Class1
Derived Class-1
Derived Class-2

Class11 Class12
Base Class-3
Base Class-2
Inheritance

Class3

Derived Class-2
#include <iostream>
using namespace std;
// first base class
class Vehicle {
public:
void display() {
cout << "This is a Vehicle" << endl;
}
};

class Car: public Vehicle {


public:
Car() {
cout << "This is a Car" << endl;
}
};
class Bus: public Vehicle {
public:
Bus() {
cout << "This is a Bus" << endl;
}
};
// Multiple inheritance
class PublicTransport: private Car, private Bus {
void display() {
cout << "This is a public transport" << endl;
}
};
// main function
int main() {
PublicTransport obj;
obj.display();
return 0;
}

Virtual Class
• Virtual base classes are used in virtual inheritance in a way of preventing multiple
“instances” of a given class appearing in an inheritance hierarchy when using multiple
inheritances.
• Need for Virtual Base Classes: Consider the situation where we have one class1 .This
class1 is inherited by two other classes; class11 and Class12. Both these class are
inherited into another in a new class3 as shown in figure below.

Base Class-1

Class1
Derived Class-1 Derived Class-2

Base Class-2 Class11 Class12 Base Class-3

Inheritance

Class3

Derived Class-2
Prog-V1

#include <iostream>
using namespace std;
class Class1 {
public:
void show() {
cout << "Hello form Class1\n";
}
};
class Class11 : public Class1{
};
class Class12 : public Class1{
};
class Class3 : public Class11, public Class12 {
};
int main() {
D object;
object.show();
return 0;
}
How declare a virtual class?
• To resolve this ambiguity when class Class1 is inherited in both class Class11 and class 12, it is
declared as virtual base class by placing a keyword virtual as :
• Syntax:
class Class11 : virtual public Class1 {};
class Class12 : public virtual Class1 {};
• virtual can be written before or after the public.
• Now only one copy of data/function member will be copied to class Class11 and class Class12
and class Class1 becomes the virtual base class.
• Virtual base classes offer a way to save space and avoid ambiguities in class hierarchies that use
multiple inheritances.
• When a base class is specified as a virtual base, it can act as an indirect base more than once
without duplication of its data members.
A single copy of its data members is shared by all the base classes that use virtual base.

#include <iostream>
using namespace std;
class Class1 {
public:
void show() {
cout << "Hello from Class1 \n";
}
};
class Class11 : public virtual Class1 {
};
class Class12: public virtual Class1 {
};
class Class3 : public Class11, public Class12 {
};
int main() {
D object;
object.show();
}

You might also like