OOP Unit 3
OOP Unit 3
BHOPAL
DEPARTMENT OF CSIT
Subject: OOPM
Code: CSIT305
Unit : III
Semester: III
L – 21 Operator overloading
Overloading unary operator
L – 22 Operator overloading
Overloading unary operator
L – 23 Overloading binary operators
L – 24 Data conversion, pitfalls of operators overloading
L – 25 Concept of inheritance, Derived class and base class, access
modifiers,
L – 26 Types of inheritance, Derived class
L – 27 member function
L – 28 public and private inheritance
L – 29 Constructors and destructor
Operator Overloading Lecture 21
3
Overloading in C++
C++ allows you to specify more than one definition for a function name or an operator
in the same scope, which is called function overloading and operator overloading
respectively.
An overloaded declaration is a declaration that had been declared with the same name
as a previously declared declaration in the same scope, except that both declarations
have different arguments and obviously different definition (implementation).
When you call an overloaded function or operator, the compiler determines the most
appropriate definition to use by comparing the argument types you used to call the
function or operator with the parameter types specified in the definitions. The process
of selecting the most appropriate overloaded function or operator is called overload
resolution.
Function overloading in C++
You can have multiple definitions for the same function name in the same scope.
The definition of the function must differ from each other by the types and/or the
number of arguments in the argument list. You cannot overload function
declarations that differ only by return type.
Following is the example where same function print() is being used to print different
data types:
#include <iostream>
using namespace std; classprintData { public:
void print(int i) {
cout<< "Printing int: " << i <<endl;
}
void print(double f) {
cout<< "Printing float: " << f <<endl;
}
void print(char* c) {
cout<< "Printing character: " << c <<endl;
}
};
int main(void) { printDatapd;
7
Operator Overloading
8
Operator Overloading
• We cannot change the....
int
main (int argc, char **argv) {
int a = 7;
int b = 8;
int c = add(a, b);
return 0;
}
Operator Overloading
class A {
friend ostream &operator<<
(ostream &, const A &);
private:
int m_;
};
ostream &operator<<
(ostream &out, const A &a) {
out << "A::m_ = " << a.m_;
return out;
}
int main () {
A a;
cout << a << endl;
return 0;
}
Operator Overloading
• An overloaded operator's operands are defined the same as arguments are defined for
functions.
• Unary operators have a single argument and binary operators have two arguments.
• When an operator is used, the operands become the actual arguments of the "function call".
• Therefore, the formal arguments must match the data type(s) expected as operands or a
conversion to those types must exist.
• I recommend that unary operators always be overloaded as members, since the first argument
must be an object of a class
13
Operator Overloading
• The return type of overloaded operators is also defined the same as it is for overloaded
functions.
• The value returned from an overloaded operator is the residual value of the expression
containing that operator and its operands.
• It is extremely important that we pay close attention to the type and value returned.
• It is the returned value that allows an operator to be used within a larger expression.
•
• It allows the result of some operation to become the operand for another operator.
• A return type of void would render an operator useless when used within an expression. (I
suggest that we never have an operator return void!)
14
Overloading operators,
Operator Overloading can be done by using three approaches, they are
Overloading unary operator.
Overloading binary operator.
Overloading binary operator using a friend function.
Below are some criteria/rules to define the operator function:
In case of a non-static function, the binary operator should have only one argument
and unary should not have an argument.
In the case of a friend function, the binary operator should have only two argument
and unary should have only one argument.
All the class member object should be public if operator overloading is
implemented.
Operators that cannot be overloaded are . .* :: ?:
Operator cannot be used to overload when declaring that function as friend
function = () [] ->.
15
Unary operators Overloading
16
Unary operators Overloading
This can be done by declaring the function, its syntax is,
Return_Type classname :: operator op(Argument list)
{
Function Body
}
In the above syntax Return_Type is value type to be returned to another
object, operator op is the function where the operator is a keyword and op is the
operator to be overloaded.
Operator function must be either non-static (member function) or friend function.
17
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--.
18
Unary operators Overloading
21
Overloading binary operators: Example
Advantages
•Reduce code redundancy.
•Provides code reusability.
•Reduces source code size and improves code readability.
•Code is easy to manage and divided into parent and child classes.
•Supports code extensibility by overriding the base class functionality within
child classes.
Disadvantages
In Inheritance base class and child classes are tightly coupled. Hence If you
change the code of parent class, it will get affects to the all the child classes.
In class hierarchy many data members remain unused and the memory allocated
to them is not utilized. Hence affect performance of your program if you have
not implemented inheritance correctly.
Another way to define a class
Inheritance..!!
28
Inheritance
The capability of a class to derive properties and characteristics from another class
is called Inheritance. Inheritance is one of the most important feature of Object
Oriented Programming.
Sub Class: The class that inherits properties from another class is called Sub
class or Derived Class.
Super Class:The class whose properties are inherited by sub class is called
Base Class or Super class.
29
• Inheritance is the capacity of a class to derive traits and properties from another
class. One of the key components of Object-Oriented Programming is
inheritance.
• New classes are produced through the process of inheritance from the current
classes. The current class is referred to as the "base class" or "parent class," and
the newly generated class is referred to as the "derived class" or "child class."
The term "inherited from the base class" now refers to the derived class.
• When we say a derived class inherits the base class, we imply that it receives all
of the base class's properties without altering them and has the option to add new
features of its own. The derived class's added features
Base & Derived Classes
A class can be derived from more than one classes, which means it can inherit
data and functions from multiple base classes. To define a derived class, we use
a class derivation list to specify the base class(es). A class derivation list names
one or more base classes and has the form:
Consider a base class Shape and its derived class Rectangle as follows:
#include <iostream> // Derived class
using namespace std; class Rectangle: public Shape { public:
// Base class class Shape intgetArea()
{ {
public: return (width * height);
voidsetWidth(int w) }
{ };
width = w; int main(void)
} {
voidsetHeight(int h) Rectangle Rect;
{ Rect.setWidth(5);
height = h; Rect.setHeight(7);
} // Print the area of the object.
protected: cout<< "Total area: " <<Rect.getArea() <<endl;
int width; int height; return 0;
}; }
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. The derived class inherits the features from the base
class and can have additional features of its own.
class Book:public Publisher
#include <iostream> {
int main()
using namespace std; string title;
{
class Publisher float price;
Book b;
{ int pages;
b.getdata();
string pname; public:
b.show();
string place; void getdata()
return 0;
public: {
}
void getdata() Publisher::getdata();
{ cout<<"Enter Book Title, Price and No. of
cout<<"Enter name and place of pages"<<endl;
publisher:"<<endl; cin>>title>>price>>pages;
cin>>pname>>place; }
} void show()
void show() {
{ Publisher:: show ();
cout<<"Publisher Name:"<<pname<<endl; cout<<"Title:"<<title<<endl;
cout<<"Place:"<<place<<endl; cout<<"Price:"<<price<<endl;
} cout<<"No. of Pages:"<<pages<<endl;
}; }
};
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 classes.
void getdata()
{
class Publisher
cout<<"Enter Author cin>>title>>price>>pages;
{
name:"<<endl; cin>>aname; }
string pname;
} void show()
string place;
void show () {
public:
{ Publisher:: show ();
void getdata()
cout<<"Author Name:"<<aname<<endl; Author:: show ();
{
} cout<<"Title:"<<title<<endl;
cout<<"Enter name and place of
}; cout<<"Price:"<<price<<endl;
publisher:"<<endl;
class Book:public Publisher, public cout<<"No. of
cin>>pname>>place;
Author Pages:"<<pages<<endl;
}
{ }
void show ()
string title; };
{
float price; int main() {
cout<<"Publisher
int pages; Book b;
Name:"<<pname<<endl;
public: b.getdata();
cout<<"Place:"<<place<<endl;
void getdata() b.show();
}
{ return 0;
};
Publisher::getdata(); }
class Author
Author::getdata();
{
cout<<"Enter Book Title, Price and No.
string aname;
of pages"<<endl;
public:
Multilevel Inheritance:
In this type of inheritance, a derived class
is created from another derived class.
#include <iostream> public:
using namespace std; void getdata()
class Publisher {
cout<<"Enter Book Title, Price
{ Publisher::getdata();
and No. of pages"<<endl;
string pname; cout<<"Enter Author
cin>>title>>price>>pages;
string place; name:"<<endl; cin>>aname;
}
public: }
void show()
void getdata() void show ()
{
{ {
Author:: show ();
cout<<"Enter name and place of Publisher:: show ();
cout<<"Title:"<<title<<endl;
publisher:"<<endl; cout<<"Author Name:"<<aname<<endl;
cout<<"Price:"<<price<<endl;
cin>>pname>>place; }
cout<<"No. of
} };
Pages:"<<pages<<endl;
void show () class Book:public Author
}
{ {
};
cout<<"Publisher string title;
int main() {
Name:"<<pname<<endl; float price;
Book b;
cout<<"Place:"<<place<<endl; int pages;
b.getdata();
} public:
b.show();
}; void getdata()
return 0;
class Author:public Publisher {
}
{ Author::getdata();
string aname;
Hierarchical Inheritance :
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.
Hybrid (Virtual) Inheritance:
Hybrid Inheritance is implemented by combining
more than one type of inheritance. For example:
Combining Hierarchical inheritance and Multiple
Inheritance.
Below image shows the combination of hierarchical
and multiple inheritance:
Public Inheritance:
Public Inheritance: When a class is derived int main()
publicly, {
all the public members of the base class B b; // DECLARATION OF OBJECT
can be accessed directly in the derived class. b.x=20;
b.y=30;
cout<<“\n member of A:”<<b.x;
// PUBLIC DERIVATION // cout<<“\n Member of
class A // BASE CLASS B:”<<b.y; return 0;
{ }
public: Output:
int x; Member of A : 20
}; Member of B : 30
class B: public A // DERIVED CLASS
{
public:
int y;
};
However, in private derivation, an object of the derived class has no permission to
directly access even public members of the base class. In such a case, the public
members of the base class can be accessed using public member functions of the
derived class.
In case the base class has private member variables and a class derived publicly, the
derived class can access the member variables of the base class using only member
functions of the base class.
The public derivation does not allow the derived class to access the private member
variable of the class directly as is possible for public member variables. The
following example illustrates public inheritance where base class members are
declared public and private.
/* Write a program to derive a class publicly from base class. Declare the base class
member under private section.*/
// PUBLIC DERIVATION //
class A // BASE CLASS
{ void showy()
private: {
int x; showx();
public: cout<<“\n y=”<<y;
A() {x=20;} }
void showx() };
{ int main()
cout<<“\n x=”<<x; {
} B b; // DECLARATION OF OBJECT
}; b.showy();
class B : public A // DERIVED CLASS return 0;
{ }
public:
int y;
B() {y=30;}
Private Inheritance:
Private Inheritance: The objects of the privately derived class cannot access the
public members of the base class directly. Hence, the member functions are used
to access the members.
/* Write a program to derive a class privately. Declare the member of base class under
public section.
class A // BASE CLASS
{ void show() {
public: cout<<“
int x; \n x=”<<x;
}; cout<<“
class B : private A // DERIVED CLASS { \n y=”<<y;
public: }
int y; };
B() { int main() {
x=20; B b; // DECLARATION OF OBJECT
y=40; b.show();
} return 0;
}
/*Write a program to derive a class privately.*/
class A // BASE CLASS {
int x; void showy()
public: {
A() { showx();
x=20; cout<<“\n y=”<<y;
} }
void showx() { };
cout<<“ int main()
\n x=”<<x; {
} B b; // DECLARATION OF OBJECT
}; b.showy();
class B : private A // DERIVED CLASS return 0;
{ }
public:
int y;
B() {
y=40;
}
Member function
A Member function is a function that is declared as a member of a class. It is declared inside the
class in any of the visibility modes
i.e. public, private, and protected, and it can access all the data members of the class. If the member
function is defined inside the class definition, it can be defined directly inside the class; otherwise,
we need to use the scope resolution operator (::) to declare the member function in C++ outside the
class(we will see about it later in the article).
The main aim of using the member function is to provide modularity to a program, which is generally
used to improve code reusability and to make code maintainable.
Definition
A member function of a class is a function that has its definition or its prototype within the class
definition like any other variable.
Member function in C++ operates on any object of the class of which it is a member and has
access to all the members of a class for that object. Therefore, we need to declare an object of a
class to access member functions of that particular class.
50
Constructor Rules for Derived Classes
The default constructor and the destructor of the base class are
always called when a new object of a derived class is created or
destroyed.
void print(); } r = c;
}
Circle C;
Point A; void print(); }
C.set(10,10,100); // from class Circle
A.set(30,50); // from base class C.foo (); // from base class Point
Point C.print(); // from class Circle
A.print(); // from base class Point 55
Key Properties of C++ Inheritance
The “is-a” relationship is maintained
A pointer to the base type may point to a derived type object
The above relationship combined with dynamic binding -
promotes a type-secure, polymorphic style of programming
The programmer need not know the actual type of an object at
compile-time (dynamic-binding)
References
Data Structures with C++, William Ford and
William Topp
Single and Multiple Inheritance in C++, Douglas
Schmidt
References
1. Object Oriented Programming With C++, Fourth Edition, E BALAGURUSAMY.
2. E. Balaguruswami, ”Object Oriented Programming in C++”, TMH. 2. Robert
Lafore, “Object Oriented Programming in C++”, Pearson. 3. M.T.
Somashekare, D.S. Guru, “ Object-Oriented Programming with C++”, PHI.
4. Herbert Shildt, “The Complete Reference C++”, Tata McGraw Hill
publication.
3. https://www.geeksforgeeks.org/passing-and-returning-objects-in-c/
4. https://ecomputernotes.com/cpp/classes-in-c/creating-objects-and-allocate-memory-fo
r-objects
5. https://www.geeksforgeeks.org/how-to-initialize-array-of-objects-with-parameterized-c
onstructors-in-c/
6. https://tutorialink.com/cpp/array-of-objects-in-cpp.cpp
7. https://www.geeksforgeeks.org
8. https://www.geeksforgeeks.org/types-of-operator-overloading-in-c/
Thank you !
Stay Tuned and Keep
Learning
www.sirtbhopal.ac.in