0% found this document useful (0 votes)
5 views56 pages

UNIT-3 Operator Overloading and Inheritance

The document discusses operator overloading and inheritance in C++. It explains how to overload operators using special functions and provides examples of unary and binary operator overloading. Additionally, it covers the concept of inheritance, its types, and how to create derived classes in C++.

Uploaded by

satyamyadav62028
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views56 pages

UNIT-3 Operator Overloading and Inheritance

The document discusses operator overloading and inheritance in C++. It explains how to overload operators using special functions and provides examples of unary and binary operator overloading. Additionally, it covers the concept of inheritance, its types, and how to create derived classes in C++.

Uploaded by

satyamyadav62028
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 56

UNIT-3 Operator Overloading and

Inheritance
C++ provides a special function to change the current functionality of some operators within its
class which is often called as operator overloading. Operator Overloading is the method by
which we can change the function of some specific operators to do some different tasks.

Syntax:
Return_Type classname :: operator op(Argument list)
{
Return_Type is the value type to be
Function Body returned to another object.
} operator op is the function where the
operator is a keyword.
op is the operator to be overloaded.
•OVERLOADING UNARY OPERATOR
• #include<iostream>
#include<cstdlib>
using namespace std;
float area(float r)
{
return(3.14 * r * r);
} do
float area(float b,float h) {
{ cout<<"\n\n *****Menu***** \n";
return(0.5 * b * h); cout<<"\n 1. Area of Circle";
} cout<<"\n 2. Area of Triangle";
float area(float l,float b) cout<<"\n 3. Area of Rectangle";
{ cout<<"\n 4. Exit";
return (l * b); cout<<"\n\n Enter Your Choice : ";
} cin>>ch;
int main() switch(ch)
{ {
float b,h,r,l; case 1:
int ch; {
cout<<"\n Enter the Radius of Circle : ";
cin>>r;
cout<<"\n Area of Circle : "<<area(r);
break;
}
case 2:
{
cout<<"\n Enter the Base & Height of Triangle : ";
cin>>b>>h;
cout<<"\n Area of Triangle : "<<area(b,h);
break;
}
case 3:
{
cout<<"\n Enter the Length & Breadth of Rectangle : ";
cin>>l>>b;
cout<<"\n Area of Rectangle : "<<area(l,b);
break;
}
case 4:
exit(0);
default:
cout<<"\n Invalid Choice... ";
}
}
while(ch!=4);
return 0;
}
• The unary operators operate on a single operand and following are the
examples of Unary operators −

• The increment (++) and decrement (--) operators.


• The unary minus (-) operator.
• The logical not (!) operator.
• The unary operators operate on the object for which they were called and
normally, this operator appears on the left side of the object, as in !obj, -obj,
and ++obj but sometime they can be used as postfix as well like obj++ or obj--.
Example of overloading minus operator
#include <iostream>
using namespace std;
// method to display distance
class Distance {
void displayDistance() const {
private: cout << "F: " << feet << " I: " << inches << endl;
int feet; // 0 to infinite }
int inches; // 0 to 12 // overloaded minus (-) operator
public: Distance operator- () const {
return Distance(-feet, -inches);
// required constructors
}
Distance() { };
feet = 0; int main() {
inches = 0; Distance D1(11, 10), D2(-5, 11);
} D1 = -D1;
Distance(int f, int i) { D1.displayDistance();
D2 = -D2;
feet = f;
D2.displayDistance();
inches = i; return 0;
} }
#include <iostream>
using namespace std;
Example of Binary operator
class Box { overoading
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
public:
double getVolume(void) {
return length * breadth * height;
}
void setLength( double len ) {
length = len;
} // Overload + operator to add two Box objects.
void setBreadth( double bre ) { Box operator+(const Box& b) {
breadth = bre; Box box;
box.length = this->length + b.length;
}
box.breadth = this->breadth + b.breadth;
void setHeight( double hei ) { box.height = this->height + b.height;
height = hei; return box;
} }
};
// Main function for the program
int main() { Continued…
Box Box1; // Declare Box1 of type Box
Box Box2; // Declare Box2 of type Box
Box Box3; // Declare Box3 of type Box
double volume = 0.0; // Store the volume of a box here
// box 1 specification // volume of box 1
Box1.setLength(6.0); volume = Box1.getVolume();
cout << "Volume of Box1 : " << volume <<endl;
Box1.setBreadth(7.0); // volume of box 2
Box1.setHeight(5.0); volume = Box2.getVolume();
// box 2 specification cout << "Volume of Box2 : " << volume <<endl;
// Add two object as follows:
Box2.setLength(12.0); Box3 = Box1 + Box2;
Box2.setBreadth(13.0); // volume of box 3
Box2.setHeight(10.0); volume = Box3.getVolume();
cout << "Volume of Box3 : " << volume <<endl;
return 0;
}
Data conversion

• There can be types of situations that may come in the data conversion between
incompatible data types:
• Conversion of primitive data type to user-defined type: To perform this conversion,
the idea is to use the constructor to perform type conversion during the object
creation. Primitive → User-defined type conversion happens using a constructor that takes a primitive
type argument.

• Conversion of class object to primitive data type : In this conversion, the from type
is a class object and the to type is primitive data type. The normal form of
an overloaded casting operator function, also known as a conversion function.
#include <bits/stdc++.h>
using namespace std;
Below is the example to convert primary data type to user-
// Time Class defined data type:
class Time {
int hour;
int mins;
public:
// Default Constructor
// Driver Code
Time()
int main()
{
{
hour = 0; mins = 0; // Object of Time class
} Time T1;
Time(int t) int dur = 95;
{
hour = t / 60; // Conversion of int type to
mins = t % 60; // class type
} T1 = dur;
void Display() T1.Display();
{
return 0;
cout << "Time = " << hour<< " hrs and "<< mins << " mins\n";
}
}
};
Below is the example to convert primary data type to user-defined data type:
#include <iostream>
using namespace std;
class Distance {
int meters;
public:
// Constructor that accepts int
Distance(int m) {
meters = m;
} int main() {
int m = 100;

void showDistance() { Distance d = m; // int is converted to Distance object


cout << meters << " meters" << endl;
d.showDistance(); // Output: 100 meters
}
}; return 0;
}
Conversion of class object to primitive data type:

• Syntax:
• special "operator function" inside the class.

operator primitive_type() {
// code to return primitive type
}
This special function has no return type (not even void) — it's special!
#include <iostream>
EXAMPLE:
using namespace std;

class Distance {
int meters;
public:
Distance(int m) {
meters = m;
} int main() {
Distance d(150); // Create object with 150 meters
// Conversion operator to int int m = d; // Object automatically converted to int
operator int() {
return meters; cout << "Distance in meters = " << m << endl; // Output:
Distance in meters = 150
}
}; return 0;
}
Inheritance in C++
• The capability of a class to derive properties and characteristics from another
class is called Inheritance. Inheritance is one of the most important features of
Object-Oriented Programming.

• 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.
• 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 do we use/ need inheritance????????

Without inheritance

With inheritance
Creating derived class:
Syntax:
class <derived_class_name> : <access-specifier> <base_class_name>
{
//body
}
Where
class — keyword to create a new class
derived_class_name — name of the new class, which will inherit the base class
access-specifier — either of private, public or protected. If neither is specified, PRIVATE is
taken as default
base-class-name — name of the base class
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
{ }

Note:
o When a base class is privately inherited by the derived class, public members of the base class
becomes the 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 derived class. They are inaccessible to the
objects of the derived class.
o On the other hand, when the base class is publicly inherited by the derived class, public members of
the base class also become the public members of the derived class. Therefore, the public members
of the base class are accessible by the objects of the derived class as well as by the member functions
of the derived class.
Example: define member function without argument within the class and
outside the class

#include <iostream> cout << "Enter the Name:";


using namespace std; cin >> name;
}
class Person {
int id; void display_p()
char name[100]; {
cout << endl <<"Id: "<< id <<
public: "\nName: " << name <<endl;
void set_p() }
{ };
cout << "Enter the Id:";
cin >> id;
class Student : private Person { cout <<"Course: "<< course <<
char course[50]; "\nFee: " << fee << endl;
}
int fee;
public: };

void set_s()
int main()
{
set_p(); {

cout << "Enter the Course Name:"; Student s;


s.set_s();
cin >> course;
cout << "Enter the Course Fee:"; s.display_s();
Output:
cin >> fee; return 0; Enter the Id: 101
} Enter the Name: Dev
} Enter the Course Name: GCS
Enter the Course Fee:70000
void display_s() Id: 101
{ Name: Dev
Course: GCS
display_p(); Fee: 70000
define member function with argument outside the class
strcpy(this->name,n);
#include<iostream> }
#include<string.h> void Person::display_p()
using namespace std; {
class Person cout<<endl<<id<<"\t"<<name;
{ }
int id; class Student: private Person
char name[100]; {
char course[50];
public: int fee;
void set_p(int,char[]); public:
void display_p(); void set_s(int,char[],char[],int);
}; void display_s();
void Person::set_p(int id,char n[]) };
{
this->id=id;
void Student::set_s(int id,char n[],char c[],int f)
{
set_p(id,n);
strcpy(course,c);
fee=f;
}
void Student::display_s()
{
display_p();
cout<<"t"<<course<<"\t"<<fee;
}
Int main()
{
Student s;
s.set_s(1001,"Ram","B.Tech",2000);
s.display_s();
return 0;
}
C++ program to demonstrate implementation of Inheritance
Output: Child id is: 7
Parent id is: 91
// main function
#include <bits/stdc++.h> int main()
using namespace std; {
// Base class Child obj1;
// An object of class child has all data members //
class Parent { and member functions of class parent
public: obj1.id_c = 7;
int id_p; obj1.id_p = 91;
}; cout << "Child id is: " << obj1.id_c <<
class Child : public Parent { '\n';
cout << "Parent id is: " << obj1.id_p
public:
<< '\n';
int id_c; return 0;
}; }
Modes of Inheritance: There are 3 modes of inheritance.
• public inheritance makes public members of the base class public in the
derived class, and the protected members of the base class remain protected
in the derived class.
• protected inheritance makes the public and protected members of the base
class protected in the derived class.
• private inheritance makes the public and protected members of the base class
private in the derived class.

• Note: private members of the base class are inaccessible to the derived class.
class A { C++ Implementation to show that a derived class doesn’t inherit access to
public: private data members.
int x;
protected:
int y;
private: class C : protected A {
int z; // x is protected
// y is protected
};
// z is not accessible from C
class B : public A { };
// x is public class D : private A // 'private' is default for classes
// y is protected {
// x is private
// z is not accessible from B
// y is private
}; // z is not accessible from D
};
// C++ program to demonstrate the working of public inheritance
#include <iostream>
using namespace std; class PublicDerived : public Base {
class Base { public:
private: // function to access protected member
int pvt = 1; from Base
int getProt() {
return prot;
protected:
}
int prot = 2;
};

public: int main() {


int pub = 3; PublicDerived object1;
cout << "Private = " << object1.getPVT() <<
// function to access private member endl;
int getPVT() { cout << "Protected = " << object1.getProt() <<
return pvt; endl;
} cout << "Public = " << object1.pub << endl;
}; return 0;
}
C++ program to demonstrate the working of protected inheritance

#include <iostream>
using namespace std;
class ProtectedDerived : protected Base {
public:
class Base { // function to access protected member from Base
private: int getProt() {
int pvt = 1; return prot;
}
protected:
// function to access public member from Base
int prot = 2; int getPub() {
return pub;
public: }
int pub = 3; };

int main() {
// function to access private member
ProtectedDerived object1;
int getPVT() { cout << "Private cannot be accessed." << endl;
return pvt; cout << "Protected = " << object1.getProt() << endl;
} cout << "Public = " << object1.getPub() << endl;
}; return 0;
}
// C++ program to demonstrate the working of private inheritance
class PrivateDerived : private Base {
#include <iostream> public:
using namespace std; // function to access protected member from Base
class Base { int getProt() {
private: return prot;
int pvt = 1; }

protected: // function to access private member


int prot = 2; int getPub() {
return pub;
}
public:
};
int pub = 3;
int main() {
// function to access private member PrivateDerived object1;
int getPVT() { cout << "Private cannot be accessed." << endl;
return pvt; cout << "Protected = " << object1.getProt() << endl;
} cout << "Public = " << object1.getPub() << endl;
}; return 0;
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
{
... .. ...
};
Syntax:

class subclass_name : access_mode base_class


{
// body of subclass
};
OR
class A
{
... .. ...
};
class B: public A
{
... .. ...
};
1. Single Inheritance:

#include <bits/stdc++.h>
using namespace std;
public:
class Vehicle {
Car() {
public: cout << "This Vehicle is Car"<< endl;
Vehicle() { }
cout << "This is a Vehicle"<< endl; };
int main() {
}
}; // Creating object of sub class will
// Sub class derived from a single base classes // invoke the constructor of base classes
class Car : public Vehicle { Car obj;
return 0;
}
Multiple Inheritance
• 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. The
constructors of inherited classes are called in the same order in which they are inherited.
Syntax:
class subclass_name : access_mode base_class1, access_mode base_class2, ....
{
// body of subclass
};
Example:
class B
{
... .. ...
};
class C
{
... .. ...
};
class A: public B, public C
{
... ... ...
};
// C++ program to explain multiple inheritance
class LandVehicle {
public:
LandVehicle() { int main() {
cout << "This is a LandVehicle"<< endl;
} // Creating object of sub class will
}; // invoke the constructor of base classes.
AmphibiousVehicle obj;
class WaterVehicle { return 0;
public: }
WaterVehicle() {
cout << "This is a WaterVehicle"<< endl;
}
};
// sub class derived from two base classes
class AmphibiousVehicle : public WaterVehicle, public LandVehicle {
public:
AmphibiousVehicle() {
cout << "This is an AmphibiousVehicle"<< endl;
}
};
#include <iostream> // Class C inherits from A publicly and from B privately
using namespace std; class C : public A, private B {
public:
class A { void showC() {
public: cout << "Class C function\n";
}
void showA() {
// Accessing B's function from inside the class
cout << "Class A function\n";
void accessB() {
} showB(); // Allowed: private inheritance allows access inside the derived class
}
}; };
int main() {
C obj;
class B {
public: obj.showA(); // Allowed: A is inherited publicly
obj.showC(); // Allowed: Defined in class C
void showB() { obj.accessB(); // Allowed: C's own function
cout << "Class B function\n";
// obj.showB(); Error: B is inherited privately, so showB() is not accessible fro
} outside
return 0;
}; }
Multilevel Inheritance
In this type of inheritance, a derived class is created from another derived class.
Multilevel Inheritance in C++
Syntax:-
class C
{
... .. ...
};
class B:public C
{
... .. ...
};
class A: public B
{
... ... ...
};
// C++ program to implement Multilevel Inheritance
#include <iostream>
using namespace std;
// sub class derived from the derived
base class fourWheeler
// base class
class Car : public fourWheeler {
class Vehicle { public:
public: Car() { cout << "Car has 4
Vehicle() { cout << "This is a Vehicle\n"; } Wheels\n"; }
}; };

// main function
// first sub_class derived from class vehicle int main()
class fourWheeler : public Vehicle { {
public: // Creating object of sub class
fourWheeler() will
{ // invoke the constructor of base
classes.
cout << "Objects with 4 wheels are vehicles\n";
Car obj;
} return 0;
}; }
Hierarchical Inheritance in C++
• 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.
class A
{
// body of the class A.
} Syntax
class B : public A
{
// body of class B.
}
class C : public A
{
// body of class C.
}
class D : public A
{
// body of class D.
}
// C++ program to implement Hierarchical Inheritance
#include <iostream>
using namespace std;

// base class // second sub class


class Vehicle { class Bus : public Vehicle {
public: };
Vehicle() { cout << "This is a Vehicle\n"; }
// main function
}; int main()
{
// first sub class Car obj1;
class Car : public Vehicle { Bus obj2;
return 0;
}; }
Hybrid (Virtual) Inheritance:
• Hybrid Inheritance is implemented by combining more than one type of
inheritance. For example: Combining Hierarchical inheritance and Multiple
Inheritance.
// C++ program for Hybrid Inheritance
#include <iostream>
using namespace std;

// base class
class Vehicle {
public:
Vehicle() { cout << "This is a Vehicle\n"; } // second sub class
}; class Bus : public Vehicle, public Fare {
};
// base class
// main function
class Fare {
int main()
public:
{
Fare() { cout << "Fare of Vehicle\n"; }
}; Bus obj2;
// first sub class return 0;
class Car : public Vehicle { }
};
Derived class constructor
// C++ program to show the order of constructor calls in Multiple Inheritance

#include <iostream>
using namespace std; {
cout << "Inside second base class" << endl;
// first base class
}
class Parent1 };
{ public: class Child : public Parent1, public Parent2
// first base class's Constructor {
Parent1() public:
{
// child class's Constructor
cout << "Inside first base class" << endl;
Child()
} {
}; cout << "Inside child class" << endl;
// second base class }
class Parent2 };
{ int main() {
Child obj1;
public:
return 0;
// second base class's Constructor }
Parent2()
#include <iostream>
using namespace std; DESTRUCTOR

class A {
public:
A() { cout << "Constructor of A\n"; }
~A() { cout << "Destructor of A\n"; }
class C : public A, public B {
};
public:
C() { cout << "Constructor of C\n"; }
class B { ~C() { cout << "Destructor of C\n"; }
public: };
B() { cout << "Constructor of B\n"; }
int main() {
~B() { cout << "Destructor of B\n"; } C obj;
}; return 0;
}
// C++ program to show the order of constructor call in single inheritance

#include <iostream>
using namespace std;
class Parent
{ public:
Parent() int main() {
Child obj;
{ return 0;
cout << "Inside base class" << endl; }
}
};
class Child : public Parent
{ public:
Child()
{
cout << "Inside sub class" << endl;
}
};
How to call the parameterized constructor of base class in derived class
constructor?
#include <iostream>
using namespace std;
To call the parameterized constructor of a base
class Animal { class from a derived class constructor, use the
public: constructor initializer list in C+
Animal(string name) {
cout << "Animal is: " << name << endl;
}
};
class Dog : public Animal {
public:
Dog(string name, string breed) : Animal(name) { int main() {
cout << "Breed is: " << breed << endl; Dog myDog("Tommy", "Labrador");
} return 0;
}; }
Important Points:

• To call the parameterized constructor of base class inside the


parameterized constructor of sub class, we have to mention it explicitly.
• The parameterized constructor of base class cannot be called in default
constructor of sub class, it should be called in the parameterized
constructor of sub class.
Example 1: C++ Shadowing Base Class Member Function
#include <iostream>
using namespace std;
What will be the output?
class Base {
public:
void print() {
cout << "Base Function" << endl;
}
};
class Derived : public Base { int main() {
public: Derived derived1;
derived1.print();
void print() {
return 0;
cout << "Derived Function" << endl;
}
}
};
Example 2: C++ Access Shadowed Function From the Base Class

#include <iostream>
using namespace std;
class Base {
public:
void print() {
cout << "Base Function" << endl;
}
}; int main() {
class Derived : public Base { Derived derived1, derived2;
public: derived1.print();
void print() { // access print() function of the Base class
cout << "Derived Function" << endl; derived2.Base::print();
}
}; return 0;
}
Example 3: C++ Call Shadowed Function From Derived Class
#include <iostream>
using namespace std;
class Base {
public:
void print() {
cout << "Base Function" << endl; // call overridden function
} Base::print();
}; }
class Derived : public Base { };
public: int main() {
void print() { Derived derived1;
cout << "Derived Function" << endl; derived1.print();
return 0;
}
class PublicDerived : public Base {
C++ public Inheritance public:
// function to access protected member
#include <iostream> from Base
using namespace std; int getProt() {
class Base { return prot;
private: }
int pvt = 1; };
protected:
int prot = 2; int main() {
public: PublicDerived object1;
int pub = 3; cout << "Private = " << object1.getPVT() <<
// function to access private member endl;
int getPVT() { cout << "Protected = " << object1.getProt()
return pvt; << endl;
} cout << "Public = " << object1.pub << endl;
return 0;
};
}
Since private and protected members are not accessible from main(), we need to create public
functions getPVT() and getProt() to access them:
// Error: member "Base::pvt" is inaccessible
cout << "Private = " << object1.pvt;

// Error: member "Base::prot" is inaccessible


cout << "Protected = " << object1.prot;

Accessibility in public Inheritance

private protected public


Accessibility
members members members

Base Class Yes Yes Yes

Derived
No Yes Yes
Class

You might also like