UNIT-3 Operator Overloading and Inheritance
UNIT-3 Operator Overloading and Inheritance
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 −
• 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;
• 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
void set_s()
int main()
{
set_p(); {
• 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;
};
#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; }
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:
#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
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:
#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;
Derived
No Yes Yes
Class