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

MOD 3 Stdi

Uploaded by

sumukhchavan6
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)
32 views

MOD 3 Stdi

Uploaded by

sumukhchavan6
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/ 20

lOMoARcPSD|36522208

C++ Module -3

object oriented programming with c++ (Visvesvaraya Technological University)

Scan to open on Studocu

Studocu is not sponsored or endorsed by any college or university


Downloaded by Sumukh Chavan (sumukhchavan6@gmail.com)
lOMoARcPSD|36522208

Object Oriented Programming with C++ BCS306B

MODULE – 3

OPEATOR OVERLOADING AND INHERITANCE

Operator Overloading

Operator overloading is a compile-time polymorphism. It is an idea of giving special meaning to


an existing operator in C++ without changing its original meaning.
Example :
int a;
float b,sum;
sum = a + b;
Here, variables “a” and “b” are of types “int” and “float”, which are built-in data types. Hence
the addition operator ‘+’ can easily add the contents of “a” and “b”. This is because the
addition operator “+” is predefined to add variables of built-in data type only.

// C++ Program to Demonstrate the working/Logic behind Operator Overloading

class A
{
statements;
};

int main()
{
A a1, a2, a3;

a3 = a1 + a2;

return 0;
}

In this example, we have 3 variables “a1”, “a2” and “a3” of type “class A”. Here we are trying to
add two objects “a1” and “a2”, which are of user-defined type i.e. of type “class A” using the
“+” operator. This is not allowed, because the addition operator “+” is predefined to operate only
on built-in data types. But here, “class A” is a user-defined type, so the compiler generates an
error. This is where the concept of “Operator overloading” comes in.
Now, if the user wants to make the operator “+” add two class objects, the user has to redefine
the meaning of the “+” operator such that it adds two class objects. This is done by using the
concept of “Operator overloading”. So the main idea behind “Operator overloading” is to use

Dept of CSE , Sir MVIT Page 1

Downloaded by Sumukh Chavan (sumukhchavan6@gmail.com)


lOMoARcPSD|36522208

Object Oriented Programming with C++ BCS306B

C++ operators with class variables or class objects. Redefining the meaning of operators really
does not change their original meaning; instead, they have been given additional meaning along
with their existing ones.

In C++, you can overload a variety of operators, including arithmetic operators, comparison
operators, assignment operators, logical operators, and more.

In order to use operator overloading we have to define operator function i.e either
member function or friend function

There are two basic categories of operators that we can Overload

a. Unary Operator
Syntax as member function :-

return-type operator < symbol > ( )


{

Unary operator is overloaded using member function no arguments are needed

Syntax as Friend function :-

friend return-type operator < symbol > ( one input argument )


{

}
If unary operator is overloaded using friend one argument is needed

b. Binary Operator
Syntax as member function :-

return-type operator < symbol > ( one input argument )


{

}
If binary operator is overloaded using member function one argument is needed.
Syntax as Friend function :-

Dept of CSE , Sir MVIT Page 2

Downloaded by Sumukh Chavan (sumukhchavan6@gmail.com)


lOMoARcPSD|36522208

Object Oriented Programming with C++ BCS306B

friend return-type operator < symbol > ( two input arguments )


{

If Binary operator is overloaded using friend function two arguments is needed.

// Example program to demonstrate unary operator overloading

#include<iostream.h>
#include<conio.h>
using namespace std;

class complex
{
int a, b, c;
public:
complex( )
{

void getvalue( )
{
cout << "Enter the Two Numbers:";
cin >> a>>b;
}

void operator++( )
{
a = ++a;
b = ++b;
}

void operator--( )
{
a = --a;
b = --b;
}

void display( )
{
cout << a << "+\t" << b << "i" << endl;
}

Dept of CSE , Sir MVIT Page 3

Downloaded by Sumukh Chavan (sumukhchavan6@gmail.com)


lOMoARcPSD|36522208

Object Oriented Programming with C++ BCS306B

};

void main( )
{
clrscr( );
complex obj;
obj.getvalue();
obj++;
cout << "Increment Complex Number\n";
obj.display();
obj--;
cout << "Decrement Complex Number\n";
obj.display();
getch();
}

Sample Output :
Enter the two numbers: 3 6
Increment Complex Number
4+ 7i
Decrement Complex Number

3 + 6i

// Program to add two numbers using the binary operator overloading

#include <iostream>
using namespace std;
class Arith_num
{
// declare data member or variable
int x, y;
public:
// create a member function to take input
void input()
{
cout << " Enter the first number: ";
cin >> x;
}
void input2()
{
cout << " Enter the second number: ";
cin >> y;
}

Dept of CSE , Sir MVIT Page 4

Downloaded by Sumukh Chavan (sumukhchavan6@gmail.com)


lOMoARcPSD|36522208

Object Oriented Programming with C++ BCS306B

// overloading the binary '+' operator to add number


Arith_num operator + (Arith_num &ob)
{
// create an object
Arith_num A;
// assign values to object
A.x = x + ob.x;
return (A);
}
// display the result of binary + operator
void print()
{
cout << "The sum of two numbers is: " <<x;
}
};
int main ()
{
Arith_num x1, y1, res; // here we create object of the class Arith_num i.e x1 and y1
// accepting the values
x1.input();
y1.input();
// assign result of x1 and x2 to res
res = x1 + y1;
// call the print() function to display the results
res.print();
return 0;
}

Output

Enter the first number: 5


Enter the second number: 6
The sum of two numbers is: 11

In the above program, we take two numbers, 5 and 6, from the user and then overload the binary
plus (+) operator to perform the addition that returns the sum of two numbers is 11.

Dept of CSE , Sir MVIT Page 5

Downloaded by Sumukh Chavan (sumukhchavan6@gmail.com)


lOMoARcPSD|36522208

Object Oriented Programming with C++ BCS306B

Example to Understand Operator Overloading in C++ Using Friend Function

#include <iostream>
using namespace std;
class Complex
{
private:
int real;
int img;
public:
Complex (int r = 0, int i = 0)
{
real = r;
img = i;
}
void Display ()
{
cout << real << "+i" << img;
}
friend Complex operator + (Complex c1, Complex c2);
};

Complex operator + (Complex c1, Complex c2)


{
Complex temp;
temp.real = c1.real + c2.real;
temp.img = c1.img + c2.img;
return temp;
}

int main ()
{
Complex C1(5, 3), C2(10, 5), C3;
C1.Display();
cout << " + ";
C2.Display();
cout << " = ";
C3 = C1 + C2;
C3.Display();
}

Dept of CSE , Sir MVIT Page 6

Downloaded by Sumukh Chavan (sumukhchavan6@gmail.com)


lOMoARcPSD|36522208

Object Oriented Programming with C++ BCS306B

In the above example, we have created two integer type private data members real and img.
Then we overloaded the + operator with two parameters C1 and C2. We have not defined
the body here. We have made it a friend by using the friend function. This is the prototype
of the friend function in C++. This function will return an object of type Complex. So, this
friend function will take two complex numbers as parameters and return a Complex number.

C3 = C1 + C2;

It is just like there is a function that will take C1 and C2 as parameters and add them and
return the result. So, neither C1 nor C2 adding but someone else is adding. This friend
function has to be written outside the class without using scope resolution. Now let us write
the body of the friend function ‘operator +’ outside the class,

Complex operator + (Complex C1, Complex C2)


{
Complex t;
t.real = C1.real + C2.real;
t.img = C1.img + C2.img;
return t;
}
This function doesn’t belong to the class but it is a friend of the Complex class. So, we don’t use
any scope resolution operator. So, this is another approach to overloading operators in C++. So,
operators, we can overload as a member function as well as we can overload them as friend
functions.

List of operators that can Not be Overloaded :-

a. Member Access Operators :- . & .*

b. Scope Resolution Operator :- ::

c. Size of Operator :- sizeof (data or data-type)


d. Conditional Operator (ternary operator) :- ? :

Dept of CSE , Sir MVIT Page 7

Downloaded by Sumukh Chavan (sumukhchavan6@gmail.com)


lOMoARcPSD|36522208

Object Oriented Programming with C++ BCS306B

Overloading New and Delete operator

The new and delete operators can also be overloaded like other operators in C++. New and
Delete operators can be overloaded globally or they can be overloaded for specific classes.

If these operators are overloaded using member function for a class, it means that these operators
are overloaded only for that specific class.
If overloading is done outside a class (i.e. it is not a member function of a class), the overloaded
‘new’ and ‘delete’ will be called anytime you make use of these operators (within classes or
outside classes). This is global overloading.

The syntax for overloading the new operator :

void* operator new(size_t size);

The overloaded new operator receives size of type size_t, which specifies the number of bytes of
memory to be allocated. The return type of the overloaded new must be void*.The overloaded
function returns a pointer to the beginning of the block of memory allocated.

Syntax for overloading the delete operator :

void operator delete(void*);

The function receives a parameter of type void* which has to be deleted. Function should not
return anything.

NOTE: Both overloaded new and delete operator functions are static members by default.
Therefore, they don’t have access to this pointer .
Overloading new and delete operator for a specific class:

// program to demonstrate Overloading new and delete operator for a specific class
#include<iostream>
#include<stdlib.h>

using namespace std;


class student
{
string name;
int age;
public:
student()

Dept of CSE , Sir MVIT Page 8

Downloaded by Sumukh Chavan (sumukhchavan6@gmail.com)


lOMoARcPSD|36522208

Object Oriented Programming with C++ BCS306B

{
cout<< "Constructor is called\n" ;
}
student(string name, int age)
{
this->name = name;
this->age = age;
}
void display()
{
cout<< "Name:" << name << endl;
cout<< "Age:" << age << endl;
}
void * operator new(size_t size)
{
cout<< "Overloading new operator with size: " << size << endl;
void * p = ::operator new(size);
//void * p = malloc(size); will also work fine
return p;
}

void operator delete(void * p)


{
cout<< "Overloading delete operator " << endl;
free(p);
}
};

int main()
{
student * p = new student("Yash", 24);
p->display();
delete p;
return 0;
}
Output
Overloading new operator with size: 40
Name:Yash
Age:24
Overloading delete operator

Dept of CSE , Sir MVIT Page 9

Downloaded by Sumukh Chavan (sumukhchavan6@gmail.com)


lOMoARcPSD|36522208

Object Oriented Programming with C++ BCS306B

NOTE:
In the above new overloaded function, we have allocated dynamic memory through new
operator, but it should be global new operator otherwise it will go in recursion
void *p = new student(); // this will go in recursion as new will be overloaded again and again
void *p = ::new student(); // this is correct

Global overloading of new and delete operator

// program to demonstrate Global overloading of new and delete operator

#include<iostream>
#include<stdlib.h>
using namespace std;

void * operator new(size_t size)


{
cout << "New operator overloading " << endl;
void * p = malloc(size);
return p;
}

void operator delete(void * p)


{
cout << "Delete operator overloading " << endl;
free(p);
}

int main()
{
int n = 5, i;
int * p = new int[n];

for (i = 0; i<n; i++)


p[i]= i;
cout << "Array: ";
for(i = 0; i<n; i++)
cout << p[i] << " ";

cout << endl;

delete [] p;
return 0;
}

Dept of CSE , Sir MVIT Page 10

Downloaded by Sumukh Chavan (sumukhchavan6@gmail.com)


lOMoARcPSD|36522208

Object Oriented Programming with C++ BCS306B

Output
New operator overloading
Array: 0 1 2 3 4
Delete operator overloading

NOTE: In the code above, in new overloaded function we cannot allocate memory
using ::new int[5] as it will go in recursion. We need to allocate memory using malloc only.

Why to overload new and delete?

1. The overloaded new operator function can accept arguments; therefore, a class can have
multiple overloaded new operator functions. This gives the programmer more flexibility in
customizing memory allocation for objects.

For example:

void *operator new(size_t size, char c)


{
void *ptr;
ptr = malloc(size);
if (ptr!=NULL)
*ptr = c;
return ptr;
}
main()
{
char *ch = new('#') char;
}
2. NOTE: Code will not only allocate memory for single character but will also initialize the
allocated memory with # character.

3. Overloaded new or delete operators also provide Garbage Collection for class’s object.

4. Exception handling routine can be added in overloaded new operator function.

5. We can use realloc() function in new function to re-allocate memory dynamically.


6. Overloaded new operator also enables programmers to squeeze some extra performance out
of their programs. For example, In a class, to speed up the allocation of new nodes, a list of
deleted nodes is maintained so that their memory can be reused when new nodes are allocated.
In this case, the overloaded delete operator will add nodes to the list of deleted nodes and the
overloaded new operator will allocate memory from this list rather than from the heap to speedup
memory allocation. Memory from the heap can be used when the list of deleted nodes is empty.

Dept of CSE , Sir MVIT Page 11

Downloaded by Sumukh Chavan (sumukhchavan6@gmail.com)


lOMoARcPSD|36522208

Object Oriented Programming with C++ BCS306B

INHERITANCE

1. It’s a method of implementing reusability of Classes.

2. The Members of one Class can be accumulated in another Class through Inheritance.

3. The Class which acts as the source of providing its Members for Inheritance is

called the Parent or Base Class. The Class that derives from or acquires the
Members of Base Class is called the Child or Derived Class.
4. The Private members of any Class can Not be Inherited.

5. The process of Inheritance can be categorized in to Three main Categories :-

1) Public Inheritance :- Here the Child Class acquires the Protected and

Public Members. And they Remain Protected and Public in the Child Class.
Its done by using “public “ keyword during Child Class definition.
Syntax :-
class child-class-name : public parent-class-name
{
definition of the child class
};
2) Private Inheritance :- Here the Child Class acquires the Protected and

Public Members. And they Become Private in the Child Class. Its done by
using “private “ keyword during Child Class definition.
Syntax :-
class child-class-name : private parent-class-name
{
definition of the child class
};
3) Protected Inheritance :- Here the Child Class acquires the Protected and

Public Members. And they Become Protected in the Child Class. Its done
by using “protected “ keyword during Child Class definition.

Dept of CSE , Sir MVIT Page 12

Downloaded by Sumukh Chavan (sumukhchavan6@gmail.com)


lOMoARcPSD|36522208

Object Oriented Programming with C++ BCS306B

Syntax :-

class child-class-name : protected parent-class-name


{
definition of the child class
};

6. There are Five Types of Inheritance Structures :-

1) Single Level Inheritance


2) Multilevel Inheritance

3) Multiple Inheritance

4) Hierarchical Inheritance

5) Hybrid Inheritance

Single Level Inheritance :-

Here there is one Base Class and one Derived Class.

Syntax :-
class child-class-name : <access-mode> parent-class-name
{
definition code for the child class
};

Example :
class A
{
public:
void display()
{
cout<<”\n class A display called”;
}
};

class B : public A
{
public :
void display()

Dept of CSE , Sir MVIT Page 13

Downloaded by Sumukh Chavan (sumukhchavan6@gmail.com)


lOMoARcPSD|36522208

Object Oriented Programming with C++ BCS306B

{
cout<<”\n class B display called”;
}
};

int main()
{
B obj;
obj.display();
obj.A::display();
return 0;
}

Inheriting multiple Base classes


1) Here the Child class is Inheriting more than one Parent classes at a time.
2) Syntax :-

class child-class-name : <specifier> parent1-class-name , <specifier>


parent2-class-name
{
child class definition
};

Example :

class A
{
public:
void display()
{
cout<<”\n class A display called”;
}
};

class B : public A
{
public :
void display()
{
cout<<”\n class B display called”;
}
};

Dept of CSE , Sir MVIT Page 14

Downloaded by Sumukh Chavan (sumukhchavan6@gmail.com)


lOMoARcPSD|36522208

Object Oriented Programming with C++ BCS306B

class C:public A, public B


{
public:
void display()
{
cout<<"\nClass C display() called";
}
};
int main()
{
C obj;
obj.display();
obj.B::display();
obj.A::display();
return 0;
}

Constructors and Destructors and Inheritance :-

1) When Inheritance takes place, an unnamed Instance of the Parent Class

gets created for every Object created from the Child Class.
2) As an Instance of the Parent Class is created, so the constructor of the

Parent Class also gets invoked.


3) If there is a Default Constructor in the Parent Class then it gets invoked

First and then the Child Class constructor is invoked.


4) If there are only Parameterized Constructors in the Parent Class then we

have to satisfy any of the Parameterized Constructors of the Parent Class


through All the Constructors of the Child Class.
5) Only the Immediate Child Class Constructor can call the Immediate Parent

Class Constructor to satisfy the compiler.


6) Only during Hybrid Inheritance and when we use Virtual Base class, then

we need to call the Grand Parent class constructor through the Grand Child

Dept of CSE , Sir MVIT Page 15

Downloaded by Sumukh Chavan (sumukhchavan6@gmail.com)


lOMoARcPSD|36522208

Object Oriented Programming with C++ BCS306B

class constructor and also the usual calling of immediate parent class
constructor by immediate child class constructor also needs to be followed.
If Virtual Base class is not used then the grand child can not call the grand
parent class constructor.
7) The Destructors are called in the just the Reverse order in which the

constructors were called.


i. Constructor of Parent -> Constructor of Child.
ii. Destructor of Child -> Destructor of Parent.
8) Syntax :-

child-class-constructor ( arguments if any ) : parent-class-constructor


(parameters)
{
definition of the child-class-constructor
}

Example :

class A
{
int a;
public:
A(int z)
{
cout<<"\nParameterized Constructor of Class A Called";
a=z;
}
A(int u, int v)
{
cout<<"\nOverloaded Parameterized Contructor of Class A Called";
}
void show()
{
cout<<"\n"<<a;
}
};

Dept of CSE , Sir MVIT Page 16

Downloaded by Sumukh Chavan (sumukhchavan6@gmail.com)


lOMoARcPSD|36522208

Object Oriented Programming with C++ BCS306B

class B:public A
{
int b;
public:
B(int z):A(z) //Parent class A constructor getting invoked with parameter
{
cout<<"\nParameterized Constructor of Class B Called";
b=z;
}
void show()
{
cout<<"\n"<<b;
}
};

class C:public B
{
int c;
public:
C():B(0) //Parent class A constructor getting invoked with parameter
{
c=0;
cout<<"\nDefault Constructor of Class C Called";
}
C(int z):B(z) //Parent class A constructor getting invoked with parameter
{
cout<<"\nParameterized Constructor of Class C Called"; c=z;
}
void show()
{
cout<<"\n"<<c;
}
};
int main()
{
C ob;
ob.A::show();
ob.B::show();
ob.show();
C ob2(10);
ob2.A::show();
ob2.B::show();
ob2.show();
return 0;
}

Dept of CSE , Sir MVIT Page 17

Downloaded by Sumukh Chavan (sumukhchavan6@gmail.com)


lOMoARcPSD|36522208

Object Oriented Programming with C++ BCS306B

Virtual Base classes


virtual base class is a class that serves as a common base class for multiple derived classes.
When a base class is marked as virtual, it helps in avoiding certain issues related to multiple
inheritance.

Example :
#include <iostream>
using namespace std;
class Animal
{
public:
virtual void sound()
{
cout << "Animal sound" << endl;
}
};

class Mammal : virtual public Animal


{

};

class Bird : virtual public Animal


{

};

class Bat : public Mammal, public Bird


{
public:
// The Bat class doesn't need to override the sound() function
// because it's already implemented in the virtual base class Animal.
};

int main()
{
Bat bat;

// Calling the sound function through the Bat object


bat.sound();
return 0;
}

Dept of CSE , Sir MVIT Page 18

Downloaded by Sumukh Chavan (sumukhchavan6@gmail.com)


lOMoARcPSD|36522208

Object Oriented Programming with C++ BCS306B

In this example:

Animal is the virtual base class. Mammal and Bird are two classes that inherit virtually from
Animal. Bat is a class that inherits from both Mammal and Bird.

By using the virtual keyword when inheriting, you ensure that there is only one instance of the
Animal subobject shared among the Mammal and Bird subobjects within the Bat class. This
avoids the duplication of the Animal subobject, which is a common issue in multiple inheritance
scenarios.

The virtual inheritance helps prevent ambiguity and ensures that there is a single path to reach
the virtual base class in the class hierarchy.

Dept of CSE , Sir MVIT Page 19

Downloaded by Sumukh Chavan (sumukhchavan6@gmail.com)

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy