SlideShare a Scribd company logo
1 of 62
CONSTRUCTORS, DESTRUCTORS AND OPERATOR OVERLOADING
1. Constructors,
2. Multiple constructors in a class,
3. Copy constructor,
4. Dynamic constructor,
5. Destructors,
6. Operator overloading,
7. Overloading Unary and binary operators,
8. Manipulation of strings using operators.
Ms.S.DEEPA M.E.,(Ph.d.)
Assistant Professor (SL.G)
Computer Science and Engineering
KIT-Kalaignarkarunanidhi Institute Of Technology
Constructors in C++
• Constructor in C++ is a special method that is invoked automatically at
the time of object creation.
• It is used to initialize the data members of new objects generally. The
constructor in C++ has the same name as the class or structure.
• Constructor is invoked at the time of object creation. It constructs the
values i.e. provides data for the object which is why it is known as
constructors.
• Constructor is a member function of a class, whose name is same as the
class name.
• Constructor is a special type of member function that is used to initialize
the data members for an object of a class automatically, when an object
of the same class is created.
• Constructor is invoked at the time of object creation. It constructs the
values i.e. provides data for the object that is why it is known as
constructor.
• Constructor do not return value, hence they do not have a return type.
The prototype of the constructor looks like
<class-name> (list-of-parameters);
<class-name> (list-of-parameters)
{
// constructor definition
}
The following syntax is used to define a constructor outside of a class:
<class-name>: :<class-name> (list-of parameters)
{
// constructor definition
}
There can be two types of constructors in C++.
• Default constructor
• Parameterized constructor
1.#include <iostream>
2.using namespace std;
3.class Employee
4. {
5. public:
6. Employee()
7. {
8. cout<<"Default Constructor Invoked"<<endl;
9. }
10.};
11.int main(void)
12.{
13. Employee e1; //creating an object of Employee
14. Employee e2;
15. return 0;
16.}
Default Constructor Invoked
Default Constructor Invoked
C++ Parameterized Constructor
• A constructor which has parameters is called parameterized constructor.
It is used to provide different values to distinct objects.
• Let's see the simple example of C++ Parameterized Constructor.
#include <iostream>
using namespace std;
class Employee {
public:
int id;//data member (also instance vari
able)
string name;//data member(also instanc
e variable)
float salary;
Employee(int i, string n, float s)
{
id = i;
name = n;
salary = s;
}
void display()
{
cout<<id<<" "<<name<<" "<<salary<
<endl;
}
};
int main(void) {
Employee e1 =Employee(101, "Sonoo", 89
0000); //creating an object of Employee
Employee e2=Employee(102, "Nakul", 59
000);
e1.display();
e2.display();
return 0;
}
101 Sonoo 890000
102 Nakul 59000
Multiple constructors in a class
class integer
{
int m,n;
public:
integer() // constructor first
{
m=0;
n=0;
}
integer(int a,int b)
// constructor second
{
m=a;
n=b;
}
integer(integer &i)
// constructor Third
{
m=i.m;
n=i.n;
}
};
This declares three constructor for an integer object.
• The first constructor receives no arguments, and
• The second case receive two integer arguments and
• the third receives one integer object as an argument.
• Types of Constructors
1. Default Constructors:
Default constructor is the constructor which doesn’t take any argument.
It has no parameters.
It is also called a zero-argument constructor.
// concept of Constructors
#include <iostream>
using namespace std;
class construct {
public:
int a, b;
// Default Constructor
construct()
{
a = 10;
b = 20;
}
};
int main()
{
// Default constructor called
automatically
// when the object is created
construct c;
cout << "a: " << c.a << endl <<
"b: " << c.b;
return 1;
}
Output
a: 10
b: 20
Note: Even if we do not define any constructor explicitly, the compiler
will automatically provide a default constructor implicitly.
#include<iostream>
using namespace std;
class student{
int rno;
char name[50];
double fee;
public:
student()
// Explicit Default
constructor
{
cout<<"Enter the RollNo:";
cin>>rno;
cout<<"Enter the Name:";
cin>>name;
cout<<"Enter the Fee:";
cin>>fee;
}
void display() {
cout<<endl<<rno<<"t"<<name<<
"t"<<fee;
} };
int main() {
student s;
s.display();
return 0; }
Parameterized Constructors:
It is possible to pass arguments to constructors.
Typically, these arguments help initialize an object when it is created.
To create a parameterized constructor, simply add parameters to it
the way you would to any other function.
When you define the constructor’s body, use the parameters to
initialize the object.
Note: when the parameterized constructor is defined and no default
constructor is defined explicitly, the compiler will not implicitly call the
default constructor and hence creating a simple object as
Student s;
Will flash an error
// parameterized constructors
#include <iostream>
using namespace std;
class Point {
private:
int x, y;
public:
// Parameterized Constructor
Point(int x1, int y1){
x = x1;
y = y1;
}
int getX() { return x; }
int getY() { return y; }
};
int main() {
// Constructor called
Point p1(10, 15);
// Access values assigned by
constructor
cout << "p1.x = " << p1.getX()
<< ", p1.y = " << p1.getY();
return 0;
}
• Output
p1.x = 10,
p1.y = 15
#include<iostream>
#include<string.h>
using namespace std;
class student
{
int rno;
char name[50];
double fee;
public:
student(int,char[],double);
void display();
};
student::student(int no,char n[],double f)
{
rno=no;
strcpy(name,n);
fee=f;
}
void student::display()
{
cout<<endl<<rno<<"t"<<name<<"t
"<<fee;
}
int main()
{
student s(1001,"Ram",10000);
s.display();
return 0;
}
When an object is declared in a parameterized constructor, the initial
values have to be passed as arguments to the constructor function.
The normal way of object declaration may not work. The constructors
can be called explicitly or implicitly.
Example
e = Example(0, 50); // Explicit call
Example
e(0, 50); // Implicit call
•Uses of Parameterized constructor:
1.It is used to initialize the various data elements of different
objects with different values when they are created.
2.It is used to overload constructors.
•Can we have more than one constructor in a class?
Yes, It is called Constructor Overloading.
3. Copy Constructor:
A copy constructor is a member function that initializes an object
using another object of the same class.
Whenever we define one or more non-default constructors( with
parameters ) for a class, a default constructor( without parameters )
should also be explicitly defined as the compiler will not provide a
default constructor in this case. However, it is not necessary but it’s
considered to be the best practice to always define a default
constructor.
Copy constructor takes a reference to an object of the same class as
an argument.
Sample(Sample &t)
{
id=t.id;
}
integer int1; // implicit default constructor
integer int1(1, 100); // explicit two-arg constructor
integer int1 = integer(0, 100);
// explicit two-arg constructor, implicit copy constructor
include <iostream>
using namespace std;
class point {
private:
double x, y;
public:
// Non-default Constructor
&
// default Constructor
point(double px, double py)
{ x = px, y = py; }
};
int main(void)
{
// Define an array of size
// 10 & of type point
// This line will cause
error
point a[10];
// Remove above line and
program
// will compile without
error
point b = point(5, 6);
}
// Implicit copy constructor
#include<iostream>
using namespace std;
class Sample
{ int id;
public:
void init(int x)
{
id=x;
}
void display()
{
cout<<endl<<"ID="<<id;
}
};
int main()
{
Sample obj1;
obj1.init(10);
obj1.display();
Sample obj2(obj1); //or obj2=obj1;
obj2.display();
return 0;
}
Output
ID=10
ID=10
// Example: Explicit copy constructor
#include <iostream>
using namespace std;
class Sample
{
int id;
public:
void init(int x)
{
id=x;
}
Sample(){} //default constructor with empty body
Sample(Sample &t) //copy constructor
{
id=t.id;
}
void display()
{
cout<<endl<<"ID="<<id;
}
};
int main()
{
Sample obj1;
obj1.init(10);
obj1.display();
Sample obj2(obj1); //or obj2=obj1; copy constructor called
obj2.display();
return 0;
}
#include<iostream>
#include<string.h>
using namespace std;
class student
{
int rno;
char name[50];
double fee;
public:
student(int,char[],double);
student(student &t) //copy constructor
{
rno=t.rno;
strcpy(name,t.name);
fee=t.fee;
}
void display();
};
student::student(int no,char n[],double f)
{
rno=no;
strcpy(name,n);
fee=f;
}
void student::display()
{
cout<<endl<<rno<<"t"<<name<<"t"<<fee;
}
int main()
{
student s(1001,"Manjeet",10000);
s.display();
student manjeet(s); //copy constructor called
manjeet.display();
return 0;
}
1001 Manjeet 10000
1001 Manjeet 10000
#include<iostream>
#include<string.h>
using namespace std;
class student{
int rno;
char name[50];
double fee;
public:
student(int,char[],double);
student(student &t) //copy constructor (member wise
initialization)
{
rno=t.rno
strcpy(name,t.name);
}
void display();
void disp(){
cout<<endl<<rno<<"t"<<name;
}
};
student::student(int no, char n[],double f) {
rno=no;
strcpy(name,n);
fee=f;
}
void student::display()
{
cout<<endl<<rno<<"t"<<name<<"t"<<fee;
}
int main() {
student s(1001,"Manjeet",10000);
s.display();
student manjeet(s); //copy constructor called
manjeet.disp();
return 0; }
#include<iostream>
using namespace std;
class code
{
int id;
public :
Code()
{
}
Code(int a){
Id=a;}
Code(code &x)
{
id=x.id;
}
void display()
{
cout << id;
}
};
void main()
{
code A(100); //object A is created and
initialized
code B(A); // copy constructor called
code C=A; // copy constructor called
again
code D; // D is created, not initialized
D=A; // copy constructor not called
std::cout << "n id of A:";
A.display();
std::cout<<"n id of B:";
B.display();
std::cout<<"n id if C:";
C.display();
std::cout<<"n id of D:";
D.display();
}
// COPY CONSTRUCTOR
#include<iostream>
using namespace std;
class code
{
int id;
public :
Code()
{
}
Code()
{
id=x.id;
}
void display()
{
cout << id;
}
};
void main()
{
code A(100); //object A is created and
initialized
code B(A); // copy constructor called
code C=A; // copy constructor called
again
code D; // D is created, not initialized
D=A; // copy constructor not called
std::cout << "n id of A:";
A.display();
std::cout<<"n id of B:";
B.display();
std::cout<<"n id if C:";
C.display();
std::cout<<"n id of D:";
D.display();
}
#include<iostream>
using namespace std;
class code{
int id;
public :
Code(){
}
Code(){
id=x.id;
}
void display(){
cout << id;
}
};
void main()
{
code A(100); //object A is created
and initialized
code B(A); // copy constructor called
code C=A; // copy constructor called
again
code D; // D is created, not initialized
D=A; // copy constructor not called
std::cout << "n id of A:";
A.display();
std::cout<<"n id of B:";
B.display();
std::cout<<"n id if C:";
C.display();
std::cout<<"n id of D:";
D.display();
}
• id of A: 100
id of B: 100
id of C: 100
id of D: 100
Copy constructor
• A Copy constructor is an overloaded constructor used to declare and
initialize an object from another object.
Copy Constructor is of two types:
• Default Copy constructor: The compiler defines the default copy
constructor. If the user defines no copy constructor, compiler supplies its
constructor.
• User Defined constructor: The programmer defines the user-defined
constructor.
• Syntax Of User-defined Copy Constructor:
Class_name(const class_name &old_object);
class A
{
A(A &x) // copy constructor.
{
// copyconstructor.
}
}
#include <iostream>
using namespace std;
class A
{
public:
int x;
A(int a) // parameterized construc
{
x=a;
}
A(A &i) // copy constructor
{
x = i.x;
}
};
int main()
{
A a1(20); // Calling the parame constru
A a2(a1); // Calling the copy constructor
cout<<a2.x;
return 0;
}
• 20
Copy Constructor is called in the following scenarios:
• When we initialize the object with another existing object of the same
class type. For example, Student s1 = s2, where Student is the class.
• When the object of the same class type is passed by value as an
argument.
• When the function returns the object of the same class type by value.
#include <iostream>
using namespace std;
class jtp {
int* ptr;
public:
jtp()
{
ptr = new int;
*ptr = 10;
}
void display()
{
cout<< *ptr<<endl;
}
};
int main()
{
jtp obj1;
obj1.display();
return 0;
}
Dynamic Constructor in C++ with Examples
• When allocation of memory is done dynamically using dynamic memory
allocator new in a constructor, it is known as dynamic constructor. By using
this, we can dynamically initialize the objects.
• In this we point data member of type char which is allocated memory
dynamically by new operator and when we create dynamic memory within
the constructor of class this is known as dynamic constructor.
#include <iostream>
using namespace std;
class geeks {
const char* p;
public:
// default constructor
geeks()
{
// allocating memory at run time
p = new char[6];
p = "geeks";
}
void display() { cout << p << endl;
}
};
int main()
{
geeks obj;
obj.display();
}
class geeks {
int* p;
public:
// default constructor
geeks() {
// allocating memory at run
time
p = new int;
*p = 0; }
// parameterized constructor
geeks(int x) {
p = new int;
*p = x; }
void display() {
cout << *p << endl; }
// Deallocate the dynamically
allocated memory
~geeks()
{
delete p;
}
};
int main() {
// default constructor would be
called
geeks obj1 = geeks();
obj1.display();
// parameterized constructor would
be called
geeks obj2 = geeks(7);
obj2.display(); }
Explanation:
In this integer type pointer variable is declared in class which is assigned
memory dynamically when the constructor is called.
When we create object obj1, the default constructor is called and memory is
assigned dynamically to pointer type variable and initialized with value 0.
And similarly when obj2 is created parameterized constructor is called and
memory is assigned dynamically.
C++ Destructor
• A destructor works opposite to constructor; it destructs the objects of
classes. It can be defined only once in a class. Like constructors, it is
invoked automatically.
• A destructor is defined like constructor. It must have same name as
class. But it is prefixed with a tilde sign (~).
What is a destructor?
Destructor is an instance member function that is invoked automatically whenever an
object is going to be destroyed. Meaning, a destructor is the last function that is going
to be called before an object is destroyed.
• A destructor is also a special member function like a constructor. Destructor destroys
the class objects created by the constructor.
• Destructor has the same name as their class name preceded by a tilde (~) symbol.
• It is not possible to define more than one destructor.
• The destructor is only one way to destroy the object created by the constructor.
Hence destructor can-not be overloaded.
• Destructor neither requires any argument nor returns any value.
• It is automatically called when an object goes out of scope.
• Destructor release memory space occupied by the objects created by the
constructor.
• In destructor, objects are destroyed in the reverse of an object creation.
The syntax for defining the destructor within the class:
~ <class-name>()
{
// some instructions
}
The syntax for defining the destructor outside the class:
<class-name> :: ~<class-name>()
{
// some instructions
}
#include <iostream>
using namespace std;
class Employee
{
public:
Employee()
{
cout<<"Constructor Invoked"<<
endl;
}
~Employee()
{
cout<<"Destructor Invoked"<<e
ndl;
}
};
int main(void)
{
Employee e1; //creating an object of
Employee
Employee e2; //creating an object of
Employee
return 0;
}
Constructor Invoked
Constructor Invoked
Destructor Invoked
Destructor Invoked
#include <iostream>
using namespace std;
class construct
{
public:
float area;
// Constructor with no parameters
construct()
{
area = 0;
}
// Constructor with two parameters
construct(int a, int b)
{
area = a * b;
}
void disp()
{
cout<< area<< endl;
}
};
int main()
{
// Constructor Overloading
// with two different constructors
// of class name
construct o;
construct o2( 10, 20);
o.disp();
o2.disp();
return 1;
}
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.
• In C++, we can make operators work for user-defined classes. This
means C++ has the ability to provide the operators with a special
meaning for a data type, this ability is known as operator overloading.
• For example, we can overload an operator ‘+’ in a class like String so
that we can concatenate two strings by just using +.
• Other example classes where arithmetic operators may be overloaded
are Complex Numbers, Fractional Numbers, Big integers, etc.
Example:
int a;
float b, sum;
sum = a + b;
// 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 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.
class Complex {
private:
int real, imag;
public:
Complex(int r = 0, int i = 0)
{
real = r;
imag = i;
}
// This is automatically called when '+' is
used with
// between two Complex objects
Complex operator+(Complex const&
obj)
{
Complex res;
res.real = real + obj.real;
res.imag = imag + obj.imag;
return res;
}
void print() { cout << real << " + i" <<
imag << 'n'; }
};
int main()
{
Complex c1(10, 5), c2(2, 4);
Complex c3 = c1 + c2;
c3.print();
}
C++ Operators Overloading
• Operator overloading is a compile-time polymorphism in which the operator
is overloaded to provide the special meaning to the user-defined data type.
• Operator overloading is used to overload or redefines most of the operators
available in C++.
• It is used to perform the operation on the user-defined data type.
• For example, C++ provides the ability to add the variables of the user-defined
data type that is applied to the built-in data types.
• The advantage of Operators overloading is to perform different operations on
the same operand.
Operator that cannot be overloaded are as follows:
• Scope operator (::)
• Sizeof
• member selector(.)
• member pointer selector(*)
• ternary operator(?:)
Syntax of Operator Overloading
return_type class_name : : operator op(argument_list)
{
// body of the function.
}
• Where the return type is the type of value returned by the function.
• class_name is the name of the class.
• operator op is an operator function where op is the operator being
overloaded, and the operator is the keyword.
Rules for Operator Overloading
• Existing operators can only be overloaded, but the new operators cannot be
overloaded.
• The overloaded operator contains atleast one operand of the user-defined data
type.
• We cannot use friend function to overload certain operators. However, the
member function can be used to overload those operators.
• When unary operators are overloaded through a member function take no
explicit arguments, but, if they are overloaded by a friend function, takes one
argument.
• When binary operators are overloaded through a member function takes one
explicit argument, and if they are overloaded through a friend function takes
two explicit arguments.
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.

More Related Content

Similar to CONSTRUCTORS, DESTRUCTORS AND OPERATOR OVERLOADING.pptx

Constructors & Destructors [Compatibility Mode].pdf
Constructors & Destructors [Compatibility Mode].pdfConstructors & Destructors [Compatibility Mode].pdf
Constructors & Destructors [Compatibility Mode].pdfLadallaRajKumar
 
Constructors in C++.pptx
Constructors in C++.pptxConstructors in C++.pptx
Constructors in C++.pptxRassjb
 
[OOP - Lec 13,14,15] Constructors / Destructor and its Types
[OOP - Lec 13,14,15] Constructors / Destructor and its Types[OOP - Lec 13,14,15] Constructors / Destructor and its Types
[OOP - Lec 13,14,15] Constructors / Destructor and its TypesMuhammad Hammad Waseem
 
Constructors and destructors in C++
Constructors and destructors in  C++Constructors and destructors in  C++
Constructors and destructors in C++RAJ KUMAR
 
constructors.pptx
constructors.pptxconstructors.pptx
constructors.pptxEpsiba1
 
data Structure Lecture 1
data Structure Lecture 1data Structure Lecture 1
data Structure Lecture 1Teksify
 
21CSC101T best ppt ever OODP UNIT-2.pptx
21CSC101T best ppt ever OODP UNIT-2.pptx21CSC101T best ppt ever OODP UNIT-2.pptx
21CSC101T best ppt ever OODP UNIT-2.pptxAnantjain234527
 
Oop concept in c++ by MUhammed Thanveer Melayi
Oop concept in c++ by MUhammed Thanveer MelayiOop concept in c++ by MUhammed Thanveer Melayi
Oop concept in c++ by MUhammed Thanveer MelayiMuhammed Thanveer M
 
constructorsfjy5ediykEASFul;IUWORHusi;gfb.pptx
constructorsfjy5ediykEASFul;IUWORHusi;gfb.pptxconstructorsfjy5ediykEASFul;IUWORHusi;gfb.pptx
constructorsfjy5ediykEASFul;IUWORHusi;gfb.pptxAshrithaRokkam
 

Similar to CONSTRUCTORS, DESTRUCTORS AND OPERATOR OVERLOADING.pptx (20)

Constructors & Destructors [Compatibility Mode].pdf
Constructors & Destructors [Compatibility Mode].pdfConstructors & Destructors [Compatibility Mode].pdf
Constructors & Destructors [Compatibility Mode].pdf
 
Constructors in C++.pptx
Constructors in C++.pptxConstructors in C++.pptx
Constructors in C++.pptx
 
[OOP - Lec 13,14,15] Constructors / Destructor and its Types
[OOP - Lec 13,14,15] Constructors / Destructor and its Types[OOP - Lec 13,14,15] Constructors / Destructor and its Types
[OOP - Lec 13,14,15] Constructors / Destructor and its Types
 
Constructors and destructors in C++
Constructors and destructors in  C++Constructors and destructors in  C++
Constructors and destructors in C++
 
constructors.pptx
constructors.pptxconstructors.pptx
constructors.pptx
 
Class and object C++.pptx
Class and object C++.pptxClass and object C++.pptx
Class and object C++.pptx
 
data Structure Lecture 1
data Structure Lecture 1data Structure Lecture 1
data Structure Lecture 1
 
C#2
C#2C#2
C#2
 
Object Oriented Programming using C++ - Part 4
Object Oriented Programming using C++ - Part 4Object Oriented Programming using C++ - Part 4
Object Oriented Programming using C++ - Part 4
 
Constructor,destructors cpp
Constructor,destructors cppConstructor,destructors cpp
Constructor,destructors cpp
 
Tut Constructor
Tut ConstructorTut Constructor
Tut Constructor
 
21CSC101T best ppt ever OODP UNIT-2.pptx
21CSC101T best ppt ever OODP UNIT-2.pptx21CSC101T best ppt ever OODP UNIT-2.pptx
21CSC101T best ppt ever OODP UNIT-2.pptx
 
Constructor and destructor
Constructor  and  destructor Constructor  and  destructor
Constructor and destructor
 
C++ Programming
C++ ProgrammingC++ Programming
C++ Programming
 
C++ Programming
C++ ProgrammingC++ Programming
C++ Programming
 
OOC MODULE1.pptx
OOC MODULE1.pptxOOC MODULE1.pptx
OOC MODULE1.pptx
 
12Structures.pptx
12Structures.pptx12Structures.pptx
12Structures.pptx
 
Oops lecture 1
Oops lecture 1Oops lecture 1
Oops lecture 1
 
Oop concept in c++ by MUhammed Thanveer Melayi
Oop concept in c++ by MUhammed Thanveer MelayiOop concept in c++ by MUhammed Thanveer Melayi
Oop concept in c++ by MUhammed Thanveer Melayi
 
constructorsfjy5ediykEASFul;IUWORHusi;gfb.pptx
constructorsfjy5ediykEASFul;IUWORHusi;gfb.pptxconstructorsfjy5ediykEASFul;IUWORHusi;gfb.pptx
constructorsfjy5ediykEASFul;IUWORHusi;gfb.pptx
 

Recently uploaded

Application of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptxApplication of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptx959SahilShah
 
Past, Present and Future of Generative AI
Past, Present and Future of Generative AIPast, Present and Future of Generative AI
Past, Present and Future of Generative AIabhishek36461
 
Call Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call GirlsCall Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call Girlsssuser7cb4ff
 
Heart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxHeart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxPoojaBan
 
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVRajaP95
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxJoão Esperancinha
 
main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidNikhilNagaraju
 
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfAsst.prof M.Gokilavani
 
Introduction to Microprocesso programming and interfacing.pptx
Introduction to Microprocesso programming and interfacing.pptxIntroduction to Microprocesso programming and interfacing.pptx
Introduction to Microprocesso programming and interfacing.pptxvipinkmenon1
 
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
Artificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxArtificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxbritheesh05
 
Current Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCLCurrent Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCLDeelipZope
 
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionSachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionDr.Costas Sachpazis
 
HARMONY IN THE HUMAN BEING - Unit-II UHV-2
HARMONY IN THE HUMAN BEING - Unit-II UHV-2HARMONY IN THE HUMAN BEING - Unit-II UHV-2
HARMONY IN THE HUMAN BEING - Unit-II UHV-2RajaP95
 
ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...
ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...
ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...ZTE
 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile servicerehmti665
 

Recently uploaded (20)

Application of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptxApplication of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptx
 
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCRCall Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
 
Past, Present and Future of Generative AI
Past, Present and Future of Generative AIPast, Present and Future of Generative AI
Past, Present and Future of Generative AI
 
Call Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call GirlsCall Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call Girls
 
Heart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxHeart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptx
 
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
 
main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfid
 
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
 
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
 
Introduction to Microprocesso programming and interfacing.pptx
Introduction to Microprocesso programming and interfacing.pptxIntroduction to Microprocesso programming and interfacing.pptx
Introduction to Microprocesso programming and interfacing.pptx
 
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
 
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
Artificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxArtificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptx
 
Current Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCLCurrent Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCL
 
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionSachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
 
HARMONY IN THE HUMAN BEING - Unit-II UHV-2
HARMONY IN THE HUMAN BEING - Unit-II UHV-2HARMONY IN THE HUMAN BEING - Unit-II UHV-2
HARMONY IN THE HUMAN BEING - Unit-II UHV-2
 
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptxExploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
 
ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...
ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...
ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...
 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile service
 

CONSTRUCTORS, DESTRUCTORS AND OPERATOR OVERLOADING.pptx

  • 1. CONSTRUCTORS, DESTRUCTORS AND OPERATOR OVERLOADING 1. Constructors, 2. Multiple constructors in a class, 3. Copy constructor, 4. Dynamic constructor, 5. Destructors, 6. Operator overloading, 7. Overloading Unary and binary operators, 8. Manipulation of strings using operators. Ms.S.DEEPA M.E.,(Ph.d.) Assistant Professor (SL.G) Computer Science and Engineering KIT-Kalaignarkarunanidhi Institute Of Technology
  • 2. Constructors in C++ • Constructor in C++ is a special method that is invoked automatically at the time of object creation. • It is used to initialize the data members of new objects generally. The constructor in C++ has the same name as the class or structure. • Constructor is invoked at the time of object creation. It constructs the values i.e. provides data for the object which is why it is known as constructors.
  • 3. • Constructor is a member function of a class, whose name is same as the class name. • Constructor is a special type of member function that is used to initialize the data members for an object of a class automatically, when an object of the same class is created. • Constructor is invoked at the time of object creation. It constructs the values i.e. provides data for the object that is why it is known as constructor. • Constructor do not return value, hence they do not have a return type. The prototype of the constructor looks like <class-name> (list-of-parameters);
  • 5. The following syntax is used to define a constructor outside of a class: <class-name>: :<class-name> (list-of parameters) { // constructor definition }
  • 6. There can be two types of constructors in C++. • Default constructor • Parameterized constructor
  • 7. 1.#include <iostream> 2.using namespace std; 3.class Employee 4. { 5. public: 6. Employee() 7. { 8. cout<<"Default Constructor Invoked"<<endl; 9. } 10.}; 11.int main(void) 12.{ 13. Employee e1; //creating an object of Employee 14. Employee e2; 15. return 0; 16.}
  • 9. C++ Parameterized Constructor • A constructor which has parameters is called parameterized constructor. It is used to provide different values to distinct objects. • Let's see the simple example of C++ Parameterized Constructor.
  • 10. #include <iostream> using namespace std; class Employee { public: int id;//data member (also instance vari able) string name;//data member(also instanc e variable) float salary; Employee(int i, string n, float s) { id = i; name = n; salary = s; } void display() { cout<<id<<" "<<name<<" "<<salary< <endl; } }; int main(void) { Employee e1 =Employee(101, "Sonoo", 89 0000); //creating an object of Employee Employee e2=Employee(102, "Nakul", 59 000); e1.display(); e2.display(); return 0; }
  • 11. 101 Sonoo 890000 102 Nakul 59000
  • 12. Multiple constructors in a class class integer { int m,n; public: integer() // constructor first { m=0; n=0; } integer(int a,int b) // constructor second { m=a; n=b; } integer(integer &i) // constructor Third { m=i.m; n=i.n; } };
  • 13. This declares three constructor for an integer object. • The first constructor receives no arguments, and • The second case receive two integer arguments and • the third receives one integer object as an argument.
  • 14. • Types of Constructors 1. Default Constructors: Default constructor is the constructor which doesn’t take any argument. It has no parameters. It is also called a zero-argument constructor.
  • 15. // concept of Constructors #include <iostream> using namespace std; class construct { public: int a, b; // Default Constructor construct() { a = 10; b = 20; } }; int main() { // Default constructor called automatically // when the object is created construct c; cout << "a: " << c.a << endl << "b: " << c.b; return 1; }
  • 16. Output a: 10 b: 20 Note: Even if we do not define any constructor explicitly, the compiler will automatically provide a default constructor implicitly.
  • 17. #include<iostream> using namespace std; class student{ int rno; char name[50]; double fee; public: student() // Explicit Default constructor { cout<<"Enter the RollNo:"; cin>>rno; cout<<"Enter the Name:"; cin>>name; cout<<"Enter the Fee:"; cin>>fee; } void display() { cout<<endl<<rno<<"t"<<name<< "t"<<fee; } }; int main() { student s; s.display(); return 0; }
  • 18. Parameterized Constructors: It is possible to pass arguments to constructors. Typically, these arguments help initialize an object when it is created. To create a parameterized constructor, simply add parameters to it the way you would to any other function. When you define the constructor’s body, use the parameters to initialize the object. Note: when the parameterized constructor is defined and no default constructor is defined explicitly, the compiler will not implicitly call the default constructor and hence creating a simple object as Student s; Will flash an error
  • 19. // parameterized constructors #include <iostream> using namespace std; class Point { private: int x, y; public: // Parameterized Constructor Point(int x1, int y1){ x = x1; y = y1; } int getX() { return x; } int getY() { return y; } }; int main() { // Constructor called Point p1(10, 15); // Access values assigned by constructor cout << "p1.x = " << p1.getX() << ", p1.y = " << p1.getY(); return 0; }
  • 20. • Output p1.x = 10, p1.y = 15
  • 21. #include<iostream> #include<string.h> using namespace std; class student { int rno; char name[50]; double fee; public: student(int,char[],double); void display(); }; student::student(int no,char n[],double f) { rno=no; strcpy(name,n); fee=f; } void student::display() { cout<<endl<<rno<<"t"<<name<<"t "<<fee; } int main() { student s(1001,"Ram",10000); s.display(); return 0; }
  • 22. When an object is declared in a parameterized constructor, the initial values have to be passed as arguments to the constructor function. The normal way of object declaration may not work. The constructors can be called explicitly or implicitly. Example e = Example(0, 50); // Explicit call Example e(0, 50); // Implicit call •Uses of Parameterized constructor: 1.It is used to initialize the various data elements of different objects with different values when they are created. 2.It is used to overload constructors. •Can we have more than one constructor in a class? Yes, It is called Constructor Overloading.
  • 23. 3. Copy Constructor: A copy constructor is a member function that initializes an object using another object of the same class. Whenever we define one or more non-default constructors( with parameters ) for a class, a default constructor( without parameters ) should also be explicitly defined as the compiler will not provide a default constructor in this case. However, it is not necessary but it’s considered to be the best practice to always define a default constructor. Copy constructor takes a reference to an object of the same class as an argument. Sample(Sample &t) { id=t.id; }
  • 24. integer int1; // implicit default constructor integer int1(1, 100); // explicit two-arg constructor integer int1 = integer(0, 100); // explicit two-arg constructor, implicit copy constructor
  • 25.
  • 26. include <iostream> using namespace std; class point { private: double x, y; public: // Non-default Constructor & // default Constructor point(double px, double py) { x = px, y = py; } }; int main(void) { // Define an array of size // 10 & of type point // This line will cause error point a[10]; // Remove above line and program // will compile without error point b = point(5, 6); }
  • 27. // Implicit copy constructor #include<iostream> using namespace std; class Sample { int id; public: void init(int x) { id=x; } void display() { cout<<endl<<"ID="<<id; } }; int main() { Sample obj1; obj1.init(10); obj1.display(); Sample obj2(obj1); //or obj2=obj1; obj2.display(); return 0; }
  • 29. // Example: Explicit copy constructor #include <iostream> using namespace std; class Sample { int id; public: void init(int x) { id=x; } Sample(){} //default constructor with empty body Sample(Sample &t) //copy constructor { id=t.id; } void display() { cout<<endl<<"ID="<<id; } }; int main() { Sample obj1; obj1.init(10); obj1.display(); Sample obj2(obj1); //or obj2=obj1; copy constructor called obj2.display(); return 0; }
  • 30. #include<iostream> #include<string.h> using namespace std; class student { int rno; char name[50]; double fee; public: student(int,char[],double); student(student &t) //copy constructor { rno=t.rno; strcpy(name,t.name); fee=t.fee; } void display(); }; student::student(int no,char n[],double f) { rno=no; strcpy(name,n); fee=f; } void student::display() { cout<<endl<<rno<<"t"<<name<<"t"<<fee; } int main() { student s(1001,"Manjeet",10000); s.display(); student manjeet(s); //copy constructor called manjeet.display(); return 0; }
  • 31. 1001 Manjeet 10000 1001 Manjeet 10000
  • 32. #include<iostream> #include<string.h> using namespace std; class student{ int rno; char name[50]; double fee; public: student(int,char[],double); student(student &t) //copy constructor (member wise initialization) { rno=t.rno strcpy(name,t.name); } void display(); void disp(){ cout<<endl<<rno<<"t"<<name; } }; student::student(int no, char n[],double f) { rno=no; strcpy(name,n); fee=f; } void student::display() { cout<<endl<<rno<<"t"<<name<<"t"<<fee; } int main() { student s(1001,"Manjeet",10000); s.display(); student manjeet(s); //copy constructor called manjeet.disp(); return 0; }
  • 33. #include<iostream> using namespace std; class code { int id; public : Code() { } Code(int a){ Id=a;} Code(code &x) { id=x.id; } void display() { cout << id; } }; void main() { code A(100); //object A is created and initialized code B(A); // copy constructor called code C=A; // copy constructor called again code D; // D is created, not initialized D=A; // copy constructor not called std::cout << "n id of A:"; A.display(); std::cout<<"n id of B:"; B.display(); std::cout<<"n id if C:"; C.display(); std::cout<<"n id of D:"; D.display(); }
  • 34. // COPY CONSTRUCTOR #include<iostream> using namespace std; class code { int id; public : Code() { } Code() { id=x.id; } void display() { cout << id; } }; void main() { code A(100); //object A is created and initialized code B(A); // copy constructor called code C=A; // copy constructor called again code D; // D is created, not initialized D=A; // copy constructor not called std::cout << "n id of A:"; A.display(); std::cout<<"n id of B:"; B.display(); std::cout<<"n id if C:"; C.display(); std::cout<<"n id of D:"; D.display(); }
  • 35. #include<iostream> using namespace std; class code{ int id; public : Code(){ } Code(){ id=x.id; } void display(){ cout << id; } }; void main() { code A(100); //object A is created and initialized code B(A); // copy constructor called code C=A; // copy constructor called again code D; // D is created, not initialized D=A; // copy constructor not called std::cout << "n id of A:"; A.display(); std::cout<<"n id of B:"; B.display(); std::cout<<"n id if C:"; C.display(); std::cout<<"n id of D:"; D.display(); }
  • 36. • id of A: 100 id of B: 100 id of C: 100 id of D: 100
  • 37. Copy constructor • A Copy constructor is an overloaded constructor used to declare and initialize an object from another object. Copy Constructor is of two types: • Default Copy constructor: The compiler defines the default copy constructor. If the user defines no copy constructor, compiler supplies its constructor. • User Defined constructor: The programmer defines the user-defined constructor.
  • 38.
  • 39. • Syntax Of User-defined Copy Constructor: Class_name(const class_name &old_object); class A { A(A &x) // copy constructor. { // copyconstructor. } }
  • 40. #include <iostream> using namespace std; class A { public: int x; A(int a) // parameterized construc { x=a; } A(A &i) // copy constructor { x = i.x; } }; int main() { A a1(20); // Calling the parame constru A a2(a1); // Calling the copy constructor cout<<a2.x; return 0; } • 20
  • 41. Copy Constructor is called in the following scenarios: • When we initialize the object with another existing object of the same class type. For example, Student s1 = s2, where Student is the class. • When the object of the same class type is passed by value as an argument. • When the function returns the object of the same class type by value.
  • 42. #include <iostream> using namespace std; class jtp { int* ptr; public: jtp() { ptr = new int; *ptr = 10; } void display() { cout<< *ptr<<endl; } }; int main() { jtp obj1; obj1.display(); return 0; }
  • 43. Dynamic Constructor in C++ with Examples • When allocation of memory is done dynamically using dynamic memory allocator new in a constructor, it is known as dynamic constructor. By using this, we can dynamically initialize the objects. • In this we point data member of type char which is allocated memory dynamically by new operator and when we create dynamic memory within the constructor of class this is known as dynamic constructor.
  • 44. #include <iostream> using namespace std; class geeks { const char* p; public: // default constructor geeks() { // allocating memory at run time p = new char[6]; p = "geeks"; } void display() { cout << p << endl; } }; int main() { geeks obj; obj.display(); }
  • 45. class geeks { int* p; public: // default constructor geeks() { // allocating memory at run time p = new int; *p = 0; } // parameterized constructor geeks(int x) { p = new int; *p = x; } void display() { cout << *p << endl; } // Deallocate the dynamically allocated memory ~geeks() { delete p; } }; int main() { // default constructor would be called geeks obj1 = geeks(); obj1.display(); // parameterized constructor would be called geeks obj2 = geeks(7); obj2.display(); }
  • 46. Explanation: In this integer type pointer variable is declared in class which is assigned memory dynamically when the constructor is called. When we create object obj1, the default constructor is called and memory is assigned dynamically to pointer type variable and initialized with value 0. And similarly when obj2 is created parameterized constructor is called and memory is assigned dynamically.
  • 47. C++ Destructor • A destructor works opposite to constructor; it destructs the objects of classes. It can be defined only once in a class. Like constructors, it is invoked automatically. • A destructor is defined like constructor. It must have same name as class. But it is prefixed with a tilde sign (~).
  • 48. What is a destructor? Destructor is an instance member function that is invoked automatically whenever an object is going to be destroyed. Meaning, a destructor is the last function that is going to be called before an object is destroyed. • A destructor is also a special member function like a constructor. Destructor destroys the class objects created by the constructor. • Destructor has the same name as their class name preceded by a tilde (~) symbol. • It is not possible to define more than one destructor. • The destructor is only one way to destroy the object created by the constructor. Hence destructor can-not be overloaded. • Destructor neither requires any argument nor returns any value. • It is automatically called when an object goes out of scope. • Destructor release memory space occupied by the objects created by the constructor. • In destructor, objects are destroyed in the reverse of an object creation.
  • 49. The syntax for defining the destructor within the class: ~ <class-name>() { // some instructions } The syntax for defining the destructor outside the class: <class-name> :: ~<class-name>() { // some instructions }
  • 50. #include <iostream> using namespace std; class Employee { public: Employee() { cout<<"Constructor Invoked"<< endl; } ~Employee() { cout<<"Destructor Invoked"<<e ndl; } }; int main(void) { Employee e1; //creating an object of Employee Employee e2; //creating an object of Employee return 0; }
  • 52. #include <iostream> using namespace std; class construct { public: float area; // Constructor with no parameters construct() { area = 0; } // Constructor with two parameters construct(int a, int b) { area = a * b; } void disp() { cout<< area<< endl; } }; int main() { // Constructor Overloading // with two different constructors // of class name construct o; construct o2( 10, 20); o.disp(); o2.disp(); return 1; }
  • 53. 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. • In C++, we can make operators work for user-defined classes. This means C++ has the ability to provide the operators with a special meaning for a data type, this ability is known as operator overloading. • For example, we can overload an operator ‘+’ in a class like String so that we can concatenate two strings by just using +. • Other example classes where arithmetic operators may be overloaded are Complex Numbers, Fractional Numbers, Big integers, etc. Example: int a; float b, sum; sum = a + b;
  • 54. // C++ Program to Demonstrate the // working/Logic behind Operator // Overloading class A { statements; }; int main() { A a1, a2, a3; a3 = a1 + a2; return 0; }
  • 55. • 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.
  • 56. • This is done by using the concept of “Operator overloading”. So the main idea behind “Operator overloading” is to use 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.
  • 57. class Complex { private: int real, imag; public: Complex(int r = 0, int i = 0) { real = r; imag = i; } // This is automatically called when '+' is used with // between two Complex objects Complex operator+(Complex const& obj) { Complex res; res.real = real + obj.real; res.imag = imag + obj.imag; return res; } void print() { cout << real << " + i" << imag << 'n'; } }; int main() { Complex c1(10, 5), c2(2, 4); Complex c3 = c1 + c2; c3.print(); }
  • 58. C++ Operators Overloading • Operator overloading is a compile-time polymorphism in which the operator is overloaded to provide the special meaning to the user-defined data type. • Operator overloading is used to overload or redefines most of the operators available in C++. • It is used to perform the operation on the user-defined data type. • For example, C++ provides the ability to add the variables of the user-defined data type that is applied to the built-in data types. • The advantage of Operators overloading is to perform different operations on the same operand.
  • 59. Operator that cannot be overloaded are as follows: • Scope operator (::) • Sizeof • member selector(.) • member pointer selector(*) • ternary operator(?:)
  • 60. Syntax of Operator Overloading return_type class_name : : operator op(argument_list) { // body of the function. } • Where the return type is the type of value returned by the function. • class_name is the name of the class. • operator op is an operator function where op is the operator being overloaded, and the operator is the keyword.
  • 61. Rules for Operator Overloading • Existing operators can only be overloaded, but the new operators cannot be overloaded. • The overloaded operator contains atleast one operand of the user-defined data type. • We cannot use friend function to overload certain operators. However, the member function can be used to overload those operators. • When unary operators are overloaded through a member function take no explicit arguments, but, if they are overloaded by a friend function, takes one argument. • When binary operators are overloaded through a member function takes one explicit argument, and if they are overloaded through a friend function takes two explicit arguments.
  • 62. 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.