0% found this document useful (0 votes)
15 views

OOPS Notes UNIT 2 (2)

This document covers object-oriented features of C++, focusing on function overloading, inheritance, operator overloading, and type conversion. It explains the concepts of function overloading and overriding, including examples and advantages, as well as different types of inheritance and their access modes. Additionally, it discusses unary and binary operator overloading, along with implicit and explicit type conversion.

Uploaded by

akashc7094
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)
15 views

OOPS Notes UNIT 2 (2)

This document covers object-oriented features of C++, focusing on function overloading, inheritance, operator overloading, and type conversion. It explains the concepts of function overloading and overriding, including examples and advantages, as well as different types of inheritance and their access modes. Additionally, it discusses unary and binary operator overloading, along with implicit and explicit type conversion.

Uploaded by

akashc7094
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/ 24

UNIT-II

Object Oriented Features of C++


Overloading - Function overloading, overloading member functions, Overloading
unary operators and binary operators –type conversion. Inheritance – Types of
Inheritance – Virtual base classes – abstract classes.

Function overloading
Function overloading is a feature of object-oriented programming where two or more functions
can have the same name but different parameters. When a function name is overloaded with
different jobs it is called Function Overloading. In Function Overloading “Function” name
should be the same and the arguments should be different. Function overloading can be
considered as an example of a polymorphism feature in C++.
The parameters should follow any one or more than one of the following conditions for
Function overloading:
1. Parameters should have a different type
add(int a, int b)
add(double a, double b)
2. Parameters should have a different number
add(int a, int b)
add(int a, int b, int c)
3. Parameters should have a different sequence of parameters.
add(int a, double b)
add(double a, int b)

Example Program
#include <iostream>
using namespace std;

void add(int a, int b)


{
cout << "sum = " << (a + b);
}

void add(double a, double b)


{
cout << endl << "sum = " << (a + b);
}

// Driver code
int main()
{

Thakshshila Univesity Page 1


add(10, 2);
add(5.3, 6.2);
return 0;
}

Output
sum = 12
sum = 11.5

Advantages
 Memory space is saved by using function overloading.
 The readability and consistency of the program become good.
 Function overloading allows us to get different behavior with the same function name.
 Execution of the program becomes fast.
 Function overloading is used for code reusability.
 Maintaining and debugging code becomes easy.
 It helps the application load the class method based on the parameter type.
Disadvantages
 If the function declaration of two functions differs by their return type, they cannot be
overloaded.
void area();
int area();
 If two Member function declarations are the same with the same name types or parameters
and one of them is declared static, they cannot be overloaded. Else it will throw an error.
Static void area();
int area();
Function overloading types

1. Compile-time overloading
When the compiler binds the function definition with a function call at the time program is
compiled is called compile-time overloading. During this time, functions are overloaded by
using different signatures. Signatures here mean the number of parameters, types of
parameters, and return type. Example-function overloading.

2. Runtime overloading
When the compiler binds the function definition with the function call at the time of execution of
a program is called runtime overloading.Example-function overriding.

Thakshshila Univesity Page 2


Function Overriding in C++?
Function overriding in C++ is a concept by which you can define a function of the same name
and the same function signature (parameters and their data types) in both the base class and
derived class with a different function definition. It redefines a function of the base class inside
the derived class, which overrides the base class function. Function overriding is an
implementation of the run-time polymorphism. So, it overrides the function at the run-time of the
program.

This can be done with the help of virtual functions A C++ virtual function is a member function
in the base class that you redefine in a derived class. It is declared using the virtual keyword. It is
used to tell the compiler to perform dynamic linkage or late binding on the function.

Ex program
#include <iostream>
using namespace std;
class parent_class
{
public:
virtual void print()
{
cout << "\nThis is print() method"
" of BaseClass";
}
};
class derived_class : public parent_class
{
public:
// Function Overriding - new definition of
// print method of base class
void print()
{
cout << "\nThis is print() method"
" of the Derived Class";
}
};
// Driver code
int main()
{
derived_class obj;
obj.print();
}
Output
This is print() method of the Derived Class

Thakshshila Univesity Page 3


Function Overloading vs. Function Overeriding

Function Overloading Function Overriding


S.no.
In function overriding, two functions have
In function overloading, two or more
1 the function name and same parameters, but
functions have different arguments but
one function is in the base class and the
the same method name.
other is in the derived class.
Function Signature is different. A
2 The function signature should remain the
signature means a type of parameters or
same.
the number of parameters

3 For function overloading, there is a need For function overriding, there is a need for
for one class. a minimum of two classes.

4 Resolved at compile Time. Resolved at run Time.

Overloading member functions


C++ lets you specify more than one function of the same name in the same scope. These
functions are called overloaded functions, or overloads.

Example program
#include <iostream>
using namespace std;
class Cal {
public:
int add(int a,int b){
return a + b;
}
int add(int a, int b, int c)
{
return a + b + c;
}
};
int main(void) {
Cal C; // class object declaration.
cout<<C.add(10, 20)<<endl;
cout<<C.add(12, 20, 23);
return 0;
}
Output
30
55

Thakshshila Univesity Page 4


Operator Overloading in C++
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 some specific operators’ functions to do different tasks.

Syntax:
Return_Type classname :: operator op(Argument list)
{
Function Body
}

Here,
 Return_Type is the value type to be returned to another object.
 operator is a keyword.
 op is the function name

Operator Overloading can be done by using two approaches, i.e.


1. Overloading Unary Operator.
2. Overloading Binary Operator.

Operator In C++
An operator in programming is a symbol (or a set of symbols) that designates a particular
operation or action to be carried out on data. Programmers can execute mathematical
calculations, value comparisons, value assignments, modifications and other operations by
manipulating variables and values with operators.

Thakshshila Univesity Page 5


Overloading Unary Operator
Let us consider overloading (-) unary operator. In the unary operator function, no arguments
should be passed. It works only with one class object. It is the overloading of an operator
operating on a single operand.
Example: Assume that class Distance takes two member objects i.e. feet and inches, and
creates a function by which the Distance object should decrement the value of feet and inches
by 1 (having a single operand of Distance Type).
#include <iostream>
using namespace std;

class Distance {
public:
int feet, inch;

// Constructor to initialize
// the object's value
Distance(int f, int i)
{
this->feet = f;
this->inch = i;
}

// Overloading(-) operator to
// perform decrement operation
// of Distance object
void operator-()
{
feet--;
inch--;
cout << "\nFeet & Inches(Decrement): " <<
feet << "'" << inch;
}
};

// Driver Code
int main()
{
Distance d1(8, 9);

// Use (-) unary operator by


// single operand
-d1;
return 0;
}

Thakshshila Univesity Page 6


Output
Feet & Inches(Decrement): 7'8

2. Overloading Binary Operator


In the binary operator overloading function, there should be one argument to be passed. It is
the overloading of an operator operating on two operands. Below is the C++ program to show
the overloading of the binary operator (+) using a class Distance with two distant objects.

Example program
#include <iostream>
using namespace std;

class Time {
private:
int hour;
int minute;

public:
Time() : hour(0), minute(0) {}

void in() {
cout << "Enter the time: ";
cin >> hour;
cin >> minute;
}

// Overload the + operator


Time operator + (const Time & obj) {
Time temp;
temp.hour = hour + obj.hour;
temp.minute = minute + obj.minute;
if (temp.minute>=60)
{
temp.hour+=1;
temp.minute-=60;
}
if (temp.hour>24)
temp.hour=1;
return temp;
}

void out() {
cout<<"Time is "<< hour<<"hrs "<<minute<<"min";
}
};

Thakshshila Univesity Page 7


int main() {
Time T1, T2, result;

cout << "Enter first time in hours and minutes one by one :\n";
T1.in();

cout << "Enter second time in hours and minutes one by one :\n";
T2.in();

// T1 calls the operator function


// T2 is passed as an argument to the function
result = T1 + T2;
result.out();

return 0;
}
Output
Enter first time in hours and minutes one by one :
Enter the time: 11
30
Enter second time in hours and minutes one by one :
Enter the time: 10
40
Time is 22hrs 10min

Difference between Unary and Binary Operators

S.no Aspect Unary Operators Binary Operators


1 Number of Operands Operates on one operand Operates on two operands
x + y,
-x,
2 Example a * b,
++i,
value == 10
Typically perform operations Perform operations involving
3 Operations
on a single value two values
May appear before or after the Appears between the
4 Syntax and Usage
operand operands
Used for operations like Used for arithmetic
5 Purpose
negation, increment, etc. operations, comparisons, etc.

Type Conversion in C++


A type cast is basically a conversion from one type to another.

Thakshshila Univesity Page 8


There are two types of type conversion:
1. Implicit Type Conversion
2. Explicit Type conversion

1.Implicit Type Conversion Also known as ‘automatic type conversion’.


 Done by the compiler on its own, without any external trigger from the user.
 Generally takes place when in an expression more than one data type is present. In such
condition type conversion (type promotion) takes place to avoid lose of data.
 All the data types of the variables are upgraded to the data type of the variable with
largest data type.

An example of implicit conversion

#include <iostream>
using namespace std;

int main()
{
int x = 10; // integer x
char y = 'a'; // character c

// y implicitly converted to int. ASCII


// value of 'a' is 97
x = x + y;

// x is implicitly converted to float


float z = x + 1.0;

cout << "x = " << x << endl


<< "y = " << y << endl
<< "z = " << z << endl;

return 0;
}

Output:
x = 107
y=a
z = 108

Thakshshila Univesity Page 9


2.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:
1. 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.
Syntax:
(type) expression

where type indicates the data type to which the final result is converted.

Example:

// C++ program to demonstrate


// explicit type casting

#include <iostream>
using namespace std;

int main()
{
double x = 1.2;

// Explicit conversion from double to int


int sum = (int)x + 1;

cout << "Sum = " << sum;

return 0;
}

Output:
Sum = 2

Thakshshila Univesity Page 10


Inheritance
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 in C++

Syntax of Inheritance in C++


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,
 access-specifier: Specifies the access mode which can be either of private, public or
protected. If neither is specified, private is taken as default.
 base-class-name: name of the base class.

Example:
class ABC : private XYZ {...} // private derivation
class ABC : public XYZ {...} // public derivation
class ABC : protected XYZ {...} // protected derivation
class ABC: XYZ {...} // private derivation by default

Example 1: Program to Demonstrate the Simple Inheritance of a Class


#include <iostream>
using namespace std;

// Base class that is to be inherited


class Parent {
public:
// base class members
int id_p;
void printID_p()
{
cout << "Base ID: " << id_p << endl;
}
};

// Sub class or derived publicly inheriting from Base


// Class(Parent)
class Child : public Parent {
public:
// derived class members
int id_c;
void printID_c()
{

Thakshshila Univesity Page 11


cout << "Child ID: " << id_c << endl;
}
};

// main function
int main()
{
// creating a child class object
Child obj1;

// An object of class child has all data members


// and member functions of class parent
// so we try accessing the parents method and data from
// the child class object.
obj1.id_p = 7;
obj1.printID_p();

// finally accessing the child class methods and data


// too
obj1.id_c = 91;
obj1.printID_c();

return 0;
}

Output
Base ID: 7
Child ID: 91

Modes of Inheritance in C++


Mode of inheritance controls the access level of the inherited members of the base class in the
derived class. In C++, there are 3 modes of inheritance:
 Public Mode
 Protected Mode
 Private Mode

Public Inheritance Mode


If we derive a subclass 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 the derived class.

Protected Inheritance Mode


If we derive a subclass from a Protected base class. Then both public members and protected
members of the base class will become protected in the derived class.

Thakshshila Univesity Page 12


Private Inheritance Mode
If we derive a subclass from a Private base class. Then both public members and protected
members of the base class will become private in the derived class. They can only be accessed
by the member functions of the derived class.
Private mode is the default mode that is applied when we don’t specify any mode.

Types Of Inheritance in C++


The inheritance can be classified on the basis of the relationship between the derived class and
the base class. In C++, we have 5 types of inheritances:
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 base class is
inherited by one derived class only.
Syntax
class subclass_name : access_mode base_class
{
// body of subclass
};
Example:

Implementation:
#include <iostream>
using namespace std;

// base class
class Vehicle {
public:
Vehicle() { cout << "This is a Vehicle\n"; }
};

// sub class derived from a single base classes


class Car : public Vehicle {
public:
Car() { cout << "This Vehicle is Car\n"; }
};

// main function

Thakshshila Univesity Page 13


int main()
{
// Creating object of sub class will
// invoke the constructor of base classes
Car obj;
return 0;
}

Output
This is a Vehicle
This Vehicle is Car
2. 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.
Syntax
class subclass_name : access_mode base_class1, access_mode base_class2, ....
{
// body of subclass
};
Here, the number of base classes will be separated by a comma (‘, ‘) and the access mode for
every base class must be specified and can be different.
Example:

Implementation:
#include <iostream>
using namespace std;

// first base class


class Vehicle {
public:
Vehicle() { cout << "This is a Vehicle\n"; }
};

// second base class


class FourWheeler {

Thakshshila Univesity Page 14


public:
FourWheeler() { cout << "This is a 4 Wheeler\n"; }
};

// sub class derived from two base classes


class Car : public Vehicle, public FourWheeler {
public:
Car() { cout << "This 4 Wheeler Vehical is a Car\n"; }
};

// main function
int main()
{
// Creating object of sub class will
// invoke the constructor of base classes.
Car obj;
return 0;
}

Output
This is a Vehicle
This is a 4 Wheeler
This 4 Wheeler Vehical is a Car
3. Multilevel Inheritance
In this type of inheritance, a derived class is created from another derived class and that
derived class can be derived from a base class or any other derived class. There can be any
number of levels.

Syntax
class derived_class1: access_specifier base_class
{
... .. ...
}
class derived_class2: access_specifier derived_class1
{
... .. ...
}
.....

Thakshshila Univesity Page 15


Example:

Implementation
#include <iostream>
using namespace std;

// base class
class Vehicle {
public:
Vehicle() { cout << "This is a Vehicle\n"; }
};

// first sub_class derived from class vehicle


class fourWheeler : public Vehicle {
public:
fourWheeler() { cout << "4 Wheeler Vehicles\n"; }
};

// sub class derived from the derived base class fourWheeler


class Car : public fourWheeler {
public:
Car() { cout << "This 4 Wheeler Vehical is a Car\n"; }
};

// main function
int main()
{
// Creating object of sub class will
// invoke the constructor of base classes.
Car obj;
return 0;
}

Output
This is a Vehicle
4 Wheeler Vehicles
This 4 Wheeler Vehical is a Car

Thakshshila Univesity Page 16


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 derived_class1: access_specifier base_class
{
... .. ...
}
class derived_class2: access_specifier base_class
{
... .. ...
}
Example:

Implementation
#include <iostream>
using namespace std;

// base class
class Vehicle {
public:
Vehicle() { cout << "This is a Vehicle\n"; }
};

// first sub class


class Car : public Vehicle {
public:
Car() { cout << "This Vehicle is Car\n"; }
};

// second sub class


class Bus : public Vehicle {
public:
Bus() { cout << "This Vehicle is Bus\n"; }
};

// main function
int main()
{
// Creating object of sub class will

Thakshshila Univesity Page 17


// invoke the constructor of base class.
Car obj1;
Bus obj2;
return 0;
}

Output
This is a Vehicle
This Vehicle is Car
This is a Vehicle
This Vehicle is Bus

5. Hybrid Inheritance
Hybrid Inheritance is implemented by combining more than one type of inheritance. For
example: Combining Hierarchical inheritance and Multiple Inheritance will create hybrid
inheritance in C++
There is no particular syntax of hybrid inheritance. We can just combine two of the above
inheritance types.
Example:
Below image shows one of the combinations of hierarchical and multiple inheritances:

Implementation:
#include <iostream>
using namespace std;

// base class
class Vehicle {
public:
Vehicle() { cout << "This is a Vehicle\n"; }
};

// base class
class Fare {
public:
Fare() { cout << "Fare of Vehicle\n"; }
};

Thakshshila Univesity Page 18


// first sub class
class Car : public Vehicle {
public:
Car() { cout << "This Vehical is a Car\n"; }
};

// second sub class


class Bus : public Vehicle, public Fare {
public:
Bus() { cout << "This Vehicle is a Bus with Fare\n"; }
};

// main function
int main()
{
// Creating object of sub class will
// invoke the constructor of base class.
Bus obj2;
return 0;
}

Output
This is a Vehicle
Fare of Vehicle
This Vehicle is a Bus with Fare

Virtual base 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 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.

Thakshshila Univesity Page 19


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.
Example: To show the need of Virtual Base Class in C++
CPP14
#include <iostream>
using namespace std;

class A {
public:
void show()
{
cout << "Hello from A \n";
}
};

class B : public A {
};

class C : public A {
};

class D : public B, public C {


};

int main()
{
D object;

Thakshshila Univesity Page 20


object.show();
}

Compile Errors:
prog.cpp: In function 'int main()':
prog.cpp:29:9: error: request for member 'show' is ambiguous
object.show();
^
prog.cpp:8:8: note: candidates are: void A::show()
void show()
^
prog.cpp:8:8: note: void A::show()

How to resolve this issue?


To resolve this ambiguity when class A is inherited in both class B and class C, it is declared
as virtual base class by placing a keyword virtual as :

Syntax for Virtual Base Classes:


Syntax 1:
class B : virtual public A
{
};
Syntax 2:
class C : public virtual A
{
};

Note:
virtual can be written before or after the public. Now only one copy of data/function member
will be copied to class C and class B and class A becomes the virtual base class. Virtual base
classes offer a way to save space and avoid ambiguities in class hierarchies that use multiple
inheritances.

Example
#include <iostream>
using namespace std;

class A {
public:
void show()
{
cout << "Hello from A \n";
}
};

class B : public virtual A {


};

Thakshshila Univesity Page 21


class C : public virtual A {
};

class D : public B, public C {


};

int main()
{
D object;
object.show();
}

Output
Hello from A

In C++, an abstract class is defined by having at least one pure virtual function, a function
without a concrete definition. These classes are essential in object-oriented programming,
structuring code to mirror real-life scenarios through inheritance and abstraction. Abstract
classes, which cannot be instantiated, are pivotal for expressing broad concepts and upcasting,
allowing derived classes to implement their interfaces. Utilize pointers and references for
abstract class types, and remember that any subclass failing to define the pure virtual function
becomes abstract itself. The virtual function is declared with the pure specifier (= 0).

Abstract Class in C++ Example

Let’s say we are making a calculator which returns the perimeter of the shape we put in. Think of
what kind of code you would write for such a calculator. You might start with some initial
shapes and hardcode the perimeter by making separate functions inside the Shape class.

In C++, an abstract class is defined by having at least one pure virtual function, a function
without a concrete definition. These classes are essential in object-oriented programming,
structuring code to mirror real-life scenarios through inheritance and abstraction. Abstract
classes, which cannot be instantiated, are pivotal for expressing broad concepts and upcasting,
allowing derived classes to implement their interfaces. Utilize pointers and references for
abstract class types, and remember that any subclass failing to define the pure virtual function
becomes abstract itself. The virtual function is declared with the pure specifier (= 0).

A virtual function in C++ is a member function declared within a base class and redefined by
the derived class.

A pure virtual function (or abstract function) is a virtual function with no definition/logic. It
is declared by assigning 0 at the time of declaration.

Thakshshila Univesity Page 22


Let’s take a look at an example that will make things clear.

Abstract Class in C++ Example

Let’s say we are making a calculator which returns the perimeter of the shape we put in. Think of
what kind of code you would write for such a calculator. You might start with some initial
shapes and hardcode the perimeter by making separate functions inside the Shape class.

#include<iostream>
using namespace std;

// Shape class.
class Shape {
public:

// Function to calculate the parameter, declared as pure virtual, so all the derived classes necessarily
need to implement this.
virtual int perimeter() = 0;
void width(int w) {
shape_width = w;
}
void height(int h) {
shape_height = h;
}

protected:
int shape_width;
int shape_height;
};

class Rectangle: public Shape {


public:
// Class Rectangle provided implementation of perimeter() function.
int perimeter() {
return (2 * (shape_width + shape_height));
}
};

class Square: public Shape {


public:
// Class Square provided implementation of perimeter() function.
int perimeter() {
return (4 * shape_width);
}
};

Thakshshila Univesity Page 23


int main() {
Rectangle R;
Square S;

R.width(10);
R.height(5);
S.width(10);

cout << "Perimeter of Rectangle: " << R.perimeter() << endl;


cout << "Perimeter of Square: " << S.perimeter() << endl;
return 0;
}

Output –
Perimeter of Rectangle : 30
Perimeter of Square: 40

In the above code, you can see that the function perimeter() is a pure virtual function,
the “virtual” keyword is used, and it is assigned a value of 0.

In the derived classes, Rectangle and Shape redefine the pure virtual function.

Characteristics of Abstract Class in C++

1. Abstract Classes must have at least one pure virtual function.

virtual int perimeter() = 0;

2. Abstract Classes cannot be instantiated, but pointers and references of Abstract Class
types can be created. You cannot create an object of an abstract class. Here is an example
of a pointer to an abstract class.

3. Abstract Classes are mainly used for Upcasting, which means its derived classes can use
its interface.
4. Classes that inherit the Abstract Class must implement all pure virtual functions. If they
do not, those classes will also be treated as abstract classes.

Thakshshila Univesity Page 24

You might also like