0% found this document useful (0 votes)
9 views59 pages

OOP Unit 3

Very good notes

Uploaded by

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

OOP Unit 3

Very good notes

Uploaded by

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

SAGAR INSTITUTE OF RESEARCH AND TECHNOLOGY

BHOPAL
DEPARTMENT OF CSIT

Subject: OOPM
Code: CSIT305
Unit : III
Semester: III

Prof. Vivek Rawat


Our Sister Concern
AP CSIT
SIRT | SIRTE | SIRTP | SIRTSP SIRT, Bhopal
OUTLINE

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

Overloading occurs when the same operator or function


name is used with different signatures
Both operators and functions can be overloaded
Allows us to define the behavior of operators when applied
to objects of a class
input_data is replaced by >>
display is replaced by <<
assign or copy is replaced by =

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;

// Call print to print integer pd.print(5);

// Call print to print float pd.print(500.263);

// Call print to print character pd.print("Hello C++");


return 0;
}
Operator Overloading
Operator Overloading does not allow us to alter the
meaning of operators when applied to built-in types
 one of the operands must be an object of a class
Operator Overloading does not allow us to define new
operator symbols
 we overload those provided for in the language to have meaning for a new
type of data...and there are very specific rules!
It is similar to overloading functions
 except the function name is replaced by the keyword operator followed by
the operator’s symbol

7
Operator Overloading

Different definitions must be distinguished by their


signatures (otherwise which to call is ambiguous)
 Reminder: signature is the operator/function name and the ordered
list of its argument types
 E.g., add(int,long) and add(long,int) have different signatures
 E.g., add(const Base &) and add(const Derived &) have
different signatures, even if Derived is-a Base
 Most specific match is used to select which one to call

8
Operator Overloading
• We cannot change the....

– number of operands an operator expects

– precedence and associatively of operators

– or use default arguments with operators

• We should not change...

– the meaning of the operator

(+ does not mean subtraction!)

– the nature of the operator (3+4 == 4+3)

– the data types and residual value expected

– whether it is an rvalued or lvalued result


9
Overloading vs. Overriding
 Overriding a base class member function is similar to overloading a function or
operator
 But for overriding, definitions are distinguished by their scopes rather than
by their signatures

 C++ can distinguish method definitions according to either static or dynamic


type
 Depends on whether a method is virtual or not
 Depends on whether called via a reference or pointer vs. directly on an object
 Depends on whether the call states the scope explicitly (e.g., Foo::baz();)
Function Overloading
class A {
public:
int add(int i, int j);

// not allowed, would be


// ambiguous with above:
// long add(int m, int n);

// Ok, different signature


long add(long m, long n);
};

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.

• The arguments represent the operator's operands.

• 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

 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 task.

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

Overloading Unary Operator: Let us consider to


overload (-) unary operator. In unary operator
function, no arguments should be passed. It works
only with one class objects. It is a overloading of an
operator operating on a single operand.
Example: Assume that class Distance takes two
member object i.e. feet and inches, create a
function by which Distance object should
decrement the value of feet and inches by 1 (having
single operand of Distance Type).
19
Unary operators Overloading: Example

#include <iostream>  // Driver Code


using namespace std;  int main()
 {
class Distance {
 // Declare and Initialize the constructor
public:
 Distance d1(8, 9);
// Member Object 
int feet, inch;
 // Use (-) unary operator by single operand
// Constructor to initialize the object's value  -d1;
Distance(int f, int i)
 return 0;
{
this->feet = f;  }
this->inch = i;  Output: Feet & Inches(Decrement): 7'8
}
 In the above program, it shows that no argument is
// Overloading(-) operator to perform decrement passed and no return_type value is returned, because
// operation of Distance object unary operator works on a single operand. (-) operator
void operator-()
change the functionality to its member function.
{
feet--;  Note: d2 = -d1 will not work, because operator-() does
inch--; not return any value
cout << "\nFeet & Inches(Decrement): " << feet << "'" <<
inch;
}
};
20
Overloading binary operators

Overloading Binary Operator: In binary


operator overloading function, there should be
one argument to be passed. It is overloading of
an operator operating on two operands.
Let’s take the same example of class Distance,
but this time, add two distance objects.

21
Overloading binary operators: Example

 / C++ program to show binary operator


overloading • // Constructor to initialize
 #include <iostream>

the object's value
 using namespace std; • // Parametrized Constructor

 class Distance { • Distance(int f, int i)
 public:
 // Member Object
• {
 int feet, inch; • this->feet = f;
 // No Parameter Constructor
 Distance() • this->inch = i;


{
this->feet = 0;
• }
 this->inch = 0; •
 }

 22
Overloading binary operators: Example

 // Overloading (+) operator to perform // Driver Code


addition of int main()
 // two distance object {
 Distance operator+(Distance& d2) // // Declaring and Initializing first object
Call by reference Distance d1(8, 9);
 {
 // Create an object to return // Declaring and Initializing second object
 Distance d2(10, 2);
Distance d3;

// Declaring third object
 // Perform addition of feet and Distance d3;
inches
 d3.feet = this->feet + d2.feet; // Use overloaded operator
 d3.inch = this->inch + d2.inch; d3 = d1 + d2;

 // Return the resulting object // Display the result
 return d3; cout << "\nTotal Feet & Inches: " << d3.feet << "'" <<
 } d3.inch;
 }; return 0;
 } 23
Overloading binary operators

Output: Total Feet & Inches: 18'11


Here in the above program,
See Line, Distance operator+(Distance &d2),
here return type of function is distance and it
uses call by references to pass an argument.
See Line, d3 = d1 + d2; here, d1 calls the
operator function of its class object and takes
d2 as a parameter, by which operator function
return object and the result will reflect in the
d3 object. 24
Pitfall in Overloading operators

 Though many languages allow overloading, few allow overloaded


methods to differ only on their result types. (Neither C++ nor Java
allow this kind of overloading).
 For example,
class MyClass
class MyClass {
{ int f() { ... }
float f(float a) { ... }
int f() { ... }
} is OK
float f() { ... }
} is illegal.
 This is unfortunate; methods with the same name and parameters,
but different result types, could be used to automatically convert
result values to the type demanded by the context of call. 25
Access Modifiers

Access public protected private

Same class yes yes yes

Derived classes yes yes no

Outside classes yes no no

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:

class derived-class: access-specifier base-class


Where access-specifier is one of public, protected, or private, and base-class is
the name of a previously defined class. If the access-specifier is not used, then
it is private by default.

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.

Member Function inside the Class


In this section, we will see how member functions are class Student{
defined inside the class. Before beginning, let's define name (string type)
the class. DOB (string type)
rollNo (integer type)
Year (integer type)
The above class represents a student class that
}
comprises essential details about the student. In the
following code, we are using some member functions
to get the details and to set the value of the details.
#include <iostream>
void Box::setLength( double len ) {
using namespace std;
length = len;
}
class Box {
void Box::setBreadth( double bre ) {
public:
breadth = bre;
double length; // Length of a box
}
double breadth; // Breadth of a box
void Box::setHeight( double hei ) {
double height; // Height of a box
height = hei;
}
// Member functions declaration
double getVolume(void);
void setLength( double len );
void setBreadth( double bre );
void setHeight( double hei );
};

// Member functions definitions


double Box::getVolume(void) {
return length * breadth * height;
}
// Main function for the program
int main() {
Box Box1; // Declare Box1 of type Box
Box Box2; // Declare Box2 of type Box
double volume = 0.0; // Store the volume of a box here
// box 1 specification
Box1.setLength(6.0);
Box1.setBreadth(7.0);
Box1.setHeight(5.0);
// box 2 specification
Box2.setLength(12.0);
Box2.setBreadth(13.0);
Box2.setHeight(10.0);
// volume of box 1
volume = Box1.getVolume();
cout << "Volume of Box1 : " << volume <<endl;
of box 2
volume = Box2.getVolume();
cout << "Volume of Box2 : " << volume <<endl;
return 0;
}
What to inherit?
 In principle, every member of a base class is inherited
by a derived class
 just with different access permission

 However, there are exceptions for


 constructor and destructor
 operator=() member
 friends
Since all these functions are class-specific

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.

class A { class B : public A


public: {
A() public:
{cout<< “A:default”<<endl;} B (int a)
A (int a) {cout<<“B”<<endl;}
{ }
cout<<“A:parameter”<<endl;} output: A:default B
} B test(1); 51
Constructor Rules for Derived Classes
You can also specify an constructor of the base class other
than the default constructor
DerivedClassCon ( derivedClass args ) : BaseClassCon ( baseClass
args )
{ DerivedClass constructor body }
class A { class C : public A
public: {
A() public:
{cout<< “A:default”<<endl;} C (int a) : A(a)
A (int a) {cout<<“C”<<endl;}
{cout<<“A:parameter”<<endl;} } A:parameter C
} output:
C test(1); 52
Define its Own Members
The derived class can also define its
class Point{
own members, in addition to the
members inherited from the base protected:
class int x, y;
Point x
y public:
void set(int a, int b); }
x
Circle
y protected:
r int x, y;
class Circle : public Point{ private:
private: double r;
double r; public:
public: void set(int a, int b);
void set_r(double c);
void set_r(double c); } 53
A derived class can override methods defined in its
parent class. With overriding,
 the method in the subclass has the identical signature to the
method in the base class.
 a subclass implements its own version of a base class method.

class A { class B : public A


protected: {
int x, y; public:
public: void print ()
void print () {cout<<“From B”<<endl;}
{cout<<“From } 54
Access a Method
class Point
{ class Circle : public Point{
protected: private: double r;
int x, y; public:
public:
void set (int a, int b, double c) {
void set(int a, int b)
{x=a; y=b;} Point :: set(a, b); //same name
void foo (); function call

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

You might also like