OOPS Notes UNIT 2 (2)
OOPS Notes UNIT 2 (2)
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;
// Driver code
int main()
{
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.
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
3 For function overloading, there is a need For function overriding, there is a need for
for one class. a minimum of two classes.
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
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 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.
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);
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;
}
void out() {
cout<<"Time is "<< hour<<"hrs "<<minute<<"min";
}
};
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();
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
#include <iostream>
using namespace std;
int main()
{
int x = 10; // integer x
char y = 'a'; // character c
return 0;
}
Output:
x = 107
y=a
z = 108
where type indicates the data type to which the final result is converted.
Example:
#include <iostream>
using namespace std;
int main()
{
double x = 1.2;
return 0;
}
Output:
Sum = 2
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
// main function
int main()
{
// creating a child class object
Child obj1;
return 0;
}
Output
Base ID: 7
Child ID: 91
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"; }
};
// main function
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;
// 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
{
... .. ...
}
.....
Implementation
#include <iostream>
using namespace std;
// base class
class Vehicle {
public:
Vehicle() { cout << "This is a Vehicle\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
Implementation
#include <iostream>
using namespace std;
// base class
class Vehicle {
public:
Vehicle() { cout << "This is a Vehicle\n"; }
};
// main function
int main()
{
// Creating object of sub class will
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"; }
};
// 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
class A {
public:
void show()
{
cout << "Hello from A \n";
}
};
class B : public A {
};
class C : public A {
};
int main()
{
D object;
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()
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";
}
};
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).
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.
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;
};
R.width(10);
R.height(5);
S.width(10);
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.
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.