SlideShare a Scribd company logo
C++
CONSTRUCTORS
&
DESTRUCTORS
Introduction
• A constructor in C++ is a special method that is
automatically called when an object of a class is created.
• To create a constructor, use the same name as the class,
followed by parentheses.
Constructors
• A constructor is a special member function which enables an
object to initialize itself when it is created. (In other word, it
is used to initialize all class data members.)
• It is special because its name is same as the class name.
• In C++, Constructor is automatically called when object
create.
• These constructors get invoked whenever an object of its
associated class is created.
• It is called constructor because it constructs the values of
data members of the class.
Constructor- example
class add
{
int m, n ;
public :
add (void) ;
------
};
add :: add (void)
{
m = 0; n = 0;
}
• When a class contains a constructor, it is guaranteed that an
object created by the class will be initialized automatically.
• add a ;
• Not only creates the object a of type add but also initializes
its data members m and n to zero.
continue …
Constructors
• There is no need to write any statement to invoke the
constructor function.
• If a ‘normal’ member function is defined for zero
initialization, we would need to invoke this function for
each of the objects separately.
• A constructor that accepts no parameters is called the
default constructor.
• The default constructor for class A is A : : A ( )
continue …
Characteristics of Constructors
• They should be declared in the public section.
• They are invoked automatically when the objects are
created.
• They do not have return types, not even void and they
cannot return values.
continue …
Characteristics of Constructors
• They cannot be inherited, though a derived class can call
the base class constructor.
• Like other C++ functions, Constructors can have default
arguments.
• Constructors can not be virtual.
continue …
Characteristics of Constructors
• We can not refer to their addresses.
• An object with a constructor (or destructor) can not be used
as a member of a union.
• They make ‘implicit calls’ to the operators new and delete
when memory allocation is required.
continue …
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.
#include <iostream>
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;
}
Copy Constructor
• A copy constructor is used to declare and initialize an
object from another object.
integer (integer & i) ; (to get value from other constructor)
integer I 2 ( I 1 ) ; or integer I 2 = I 1 ;
The process of initializing through a copy constructor is
known as copy initialization.
Copy Constructor
• The statement
I 2 = I 1;
will not invoke the copy constructor.
• If I 1 and I 2 are objects, this statement is legal and assigns
the values of I 1 to I 2, member-by-member.
• A reference variable has been used as an argument to the
copy constructor.
• We cannot pass the argument by value to a copy constructor.
continue …
Dynamic Constructors
• The constructors can also be used to allocate memory while
creating objects.
• This will enable the system to allocate the right amount of
memory for each object when the objects are not of the
same size.
• Allocation of memory to objects at the time of their
construction is known as dynamic construction of objects.
• The memory is created with the help of the new operator.
Destructors
• A destructor is used to destroy the objects that have been
created by a constructor.
• Like constructor, the destructor is a member function whose
name is the same as the class name but is preceded by a
tilde.
eg: ~ integer ( ) { }
• A destructor never takes any argument nor does it return
any value.
• It will be invoked implicitly by the compiler upon exit from
the program – or block or function as the case may be – to
clean up storage that is no longer accessible.
Destructors
• It is a good practice to declare destructors in a program
since it releases memory space for further use.
• Whenever new is used to allocate memory in the
constructor, we should use delete to free that memory.
continue …
OPERATOR
OVERLOADINGAND
TYPE
CONVERSIONS
Introduction
• It is one of the many exciting features of C++.
• C++ has ability to provide the operators with a special meaning
for a data types.
• We can overload (give additional meaning to) all the C++
operators except:
• Class member access operators ( . & .*)
• Scope resolution operators ( : : )
• Size operator (sizeof)
• Conditional operators (? : )
• When an operator is overloaded, its original meaning is not lost
Defining Operator Overloading
• To define an additional task to an operator, we must specify what it
means in relation to the class to which the operator is applied.
• This is done with the help of a special function called operator
function.
return type class-name : :operator op (arg-list)
{
Function body // task defined
}
DefiningOperatorOverloading
• return type is the type of value returned by the specified operation.
• op is the operator being overloaded.
• op is preceded by the keyword operator.
• operator op is the function name.
continue…
DefiningOperatorOverloading
• Operator Function must be either
member function (non-static) Or friend function.
The basic difference :
• A friend function will have only one argument for unary
operators and two for binary operators.
• A member function has no arguments for unary
operators and one argument for binary operators.
• Arguments may be passed either by value or by reference.
continue…
Process of OperatorOverloading
The process of overloading involves the following steps:
• Create a class that defines the data type that is to be used in
the overloading operation.
• Declare the operator function operator op( ) in the public part
of the class. It may be either a member function or a friend
function.
• Define the operator function to implement the required
operations.
continue…
Process of OperatorOverloading
• Overloaded operator functions can be invoked by expressions such
as:
For unary operators: op x or x op
For binary operators: x op y
• op x or x op would be interpreted as
for a friend function:operator op (x)
for a member function: x.operator op ( )
• x op y would be interpreted as
for a friend function:operator op (x,y)
for a member function: x.operator op (y)
continue…
Overloading Unary Operators
Consider a unary minus operator:
• It takes just one operand.
• It changes the sign of an operand when applied to a basic data
item.
• The unary minus when applied to an object should change the
sign of each of its data items.
Overloading Binary Operators
As a rule, in overloading binary operators,
• the left-hand operand is used to invoke the operator function
and
• the right-hand operand is passed as an argument.
Overloading Binary Operators
complex operator+(complex a, complex b)
{
return complex((a.x + b.x),(a.y + b.y));
}
• The compiler invokes an appropriate constructor, initializes an
object with no name and returns the contents for copying into an
object.
• Such an object is called a temporary object.
continue…
Overloading Binary Operators Using
Friends
• Friend function requires two arguments to be explicitly passes to
it.
• Member function requires only one.
friend complex operator+(complex, complex);
complex operator+(complex a, complex b)
{
return complex((a.x + b.x),(a.y + b.y));
}
• We can use a friend function with built-in type data as the left-
hand operand and an object as the right-hand operand.
Manipulation of Strings using
Operators
• There are lot of limitations in string manipulation in C as well as in
C++.
• Implementation of strings require character arrays, pointers
and string functions.
• C++ permits us to create our own definitions of operators that can
be used to manipulate the strings very much similar to other built-
in data types.
• ANSI C++ committee has added a new class called string to the
C++ class library that supports all kinds of string manipulations.
Manipulationof Strings using Operators
• Strings can be defined as class, objects which can be then
manipulated like the built-in types.
• Since the strings vary in size, we use new to allocate memory
for each string and a pointer variable to point to the string
array.
continue…
Manipulationof Strings using Operators
• We must create string objects that can hold two pieces of
information:
• Length
• Location
class string
{
char *p; // pointer to string
int len; // length of string
public :
------
------
};
continue…
Rules For Overloading Operators
• Only existing operators can be overloaded. New operators
cannot be created.
• The overloaded operator must have at least one operand that is
of user-defined type.
• We cannot change the basic meaning of an operator.
• Overloaded operators follow the syntax rules of the original
operators.
Rules ForOverloadingOperators
• The following operators that cannot be overloaded:
Size of Size of operator
. Membership operator
.* Pointer-to-member operator
: : Scope resolution operator
? ; Conditional operator
continue…
Rules ForOverloadingOperators
• The following operators can be over loaded with the use of
member functions and not by the use of friend functions:
• Assignment operator =
• Function call operator( )
• Subscripting operator [ ]
• Class member access operator ->
• Unary operators, overloaded by means of a member function,
take no explicit arguments and return no explicit values, but,
those overloaded by means of a friend function, take one
reference argument.
continue…
Rules ForOverloadingOperators
• Binary arithmetic operators such as +, -, * and / must explicitly
return a value. They must not attempt to change their own
arguments.
• Binary operators overloaded through a member function
take one explicit argument and those which are overloaded
through a friend function take two explicit arguments.
continue…
Type Conversions
• The type conversions are automatic only when the data types
involved are built-in types.
int m;
float x = 3.14159;
m = x; // convert x to integer before its value is assigned
// to m.
• For user defined data types, the compiler does not support
automatic type conversions.
• We must design the conversion routines by ourselves.
Type Conversions
• Different situations of data conversion between incompatible
types.
• Conversion from basic type to class type.
• Conversion from class type to basic type.
• Conversion from one class type to another class type.
continue…
Basic to ClassType
• A constructor to build a string type object from a char * type
variable.
string : : string(char *a)
{
length = strlen(a);
P = new char[length+1];
strcpy(P,a);
}
• The variables length and p are data members of the class string.
continue…
Basic to ClassType
class time
{ int hrs ;
int mins ;
public :
…
time (int t)
{
hrs = t / 60 ;
mins = t % 60;
}
} ;
time T1;
int duration = 85;
T1 = duration;
continue…
ClassTo BasicType
• A constructor function do not support type conversion from a
class type to a basic type.
• An overloaded casting operator is used to convert a class type
data to a basic type.
• It is also referred to as conversion function.
operator typename( )
{
…
… ( function statements )
…
}
• This function converts a calss type data to typename.
continue…
ClassTo BasicType
vector : : operator double( )
{
double sum = 0;
for (int i=0; i < size ; i++)
sum = sum + v[i] * v[i];
return sqrt (sum);
}
• This function converts a vector to the square root of the sum of
squares of its components.
continue…
ClassTo BasicType
• The casting operator function should satisfy the following
conditions:
• It must be a class member.
• It must not specify a return type.
• It must not have any arguments.
vector : : operator double( )
{
double sum = 0;
for (int i=0; i < size ; i++)
sum = sum + v[i] * v[i];
return sqrt (sum);
}
continue…
ClassTo BasicType
• Conversion functions are member functions and it is
invoked with objects.
• Therefore the values used for conversion inside the
function belong to the object that invoked the function.
• This means that the function does not need an argument.
continue…
One Class ToAnother Class Type
objX = objY ; // objects of different types
• objX is an object of class X and objY is an object of class Y.
• The class Y type data is converted to the class X type data and
the converted value is assigned to the objX.
• Conversion is takes place from class Y to class X.
• Y is known as source class.
• X is known as destination class.
One ClassToAnotherClassType
• Conversion between objects of different classes can be carried
out by either a constructor or a conversion function.
• Choosing of constructor or the conversion function depends upon
where we want the type-conversion function to be located in the
source class or in the destination class.
continue…
One ClassToAnotherClassType
operator typename( )
• Converts the class object of which it is a member to typename.
• The typename may be a built-in type or a user-defined one.
• In the case of conversions between objects, typename refers to
the destination class.
• When a class needs to be converted, a casting operator
function can be used at the source class.
• The conversion takes place in the source class and the result is
given to the destination class object.
continue…
One ClassToAnotherClassType
Consider a constructor function with a single argument
• Construction function will be a member of the destination
class.
• The argument belongs to the source class and is passed to the
destination class for conversion.
• The conversion constructor be placed in the destination class.
continue…

More Related Content

What's hot

MYSQL - PHP Database Connectivity
MYSQL - PHP Database ConnectivityMYSQL - PHP Database Connectivity
MYSQL - PHP Database Connectivity
V.V.Vanniaperumal College for Women
 
MVC Architecture
MVC ArchitectureMVC Architecture
MVC Architecture
Prem Sanil
 
Arrays in java
Arrays in javaArrays in java
Arrays in java
bhavesh prakash
 
Form Validation in JavaScript
Form Validation in JavaScriptForm Validation in JavaScript
Form Validation in JavaScript
Ravi Bhadauria
 
Javascript arrays
Javascript arraysJavascript arrays
Javascript arrays
Hassan Dar
 
PHP Loops and PHP Forms
PHP  Loops and PHP FormsPHP  Loops and PHP Forms
PHP Loops and PHP Forms
M.Zalmai Rahmani
 
Java IO
Java IOJava IO
Java IO
UTSAB NEUPANE
 
Introduction to Java Scripting
Introduction to Java ScriptingIntroduction to Java Scripting
Introduction to Java Scripting
fantasticdigitaltools
 
PHP variables
PHP  variablesPHP  variables
PHP variables
Siddique Ibrahim
 
Spring - Part 2 - Autowiring, Annotations, Java based Configuration - slides
Spring - Part 2 - Autowiring, Annotations, Java based Configuration - slidesSpring - Part 2 - Autowiring, Annotations, Java based Configuration - slides
Spring - Part 2 - Autowiring, Annotations, Java based Configuration - slides
Hitesh-Java
 
Js: master prototypes
Js: master prototypesJs: master prototypes
Js: master prototypes
Barak Drechsler
 
Smooth scrolling in UITableView and UICollectionView
Smooth scrolling in UITableView and UICollectionViewSmooth scrolling in UITableView and UICollectionView
Smooth scrolling in UITableView and UICollectionView
Andrea Prearo
 
Exception handling in plsql
Exception handling in plsqlException handling in plsql
Exception handling in plsql
Arun Sial
 
Collectors in the Wild
Collectors in the WildCollectors in the Wild
Collectors in the Wild
José Paumard
 
Python lambda functions with filter, map & reduce function
Python lambda functions with filter, map & reduce functionPython lambda functions with filter, map & reduce function
Python lambda functions with filter, map & reduce function
ARVIND PANDE
 
PHP Form Validation Technique
PHP Form Validation TechniquePHP Form Validation Technique
PHP Form Validation Technique
Morshedul Arefin
 
Python Datatypes by SujithKumar
Python Datatypes by SujithKumarPython Datatypes by SujithKumar
Python Datatypes by SujithKumar
Sujith Kumar
 
Creating Views - oracle database
Creating Views - oracle databaseCreating Views - oracle database
Creating Views - oracle database
Salman Memon
 
Parboiled explained
Parboiled explainedParboiled explained
Parboiled explained
Paul Popoff
 

What's hot (20)

MYSQL - PHP Database Connectivity
MYSQL - PHP Database ConnectivityMYSQL - PHP Database Connectivity
MYSQL - PHP Database Connectivity
 
MVC Architecture
MVC ArchitectureMVC Architecture
MVC Architecture
 
Arrays in java
Arrays in javaArrays in java
Arrays in java
 
Form Validation in JavaScript
Form Validation in JavaScriptForm Validation in JavaScript
Form Validation in JavaScript
 
Javascript arrays
Javascript arraysJavascript arrays
Javascript arrays
 
PHP Loops and PHP Forms
PHP  Loops and PHP FormsPHP  Loops and PHP Forms
PHP Loops and PHP Forms
 
Java IO
Java IOJava IO
Java IO
 
Introduction to Java Scripting
Introduction to Java ScriptingIntroduction to Java Scripting
Introduction to Java Scripting
 
PHP variables
PHP  variablesPHP  variables
PHP variables
 
Spring - Part 2 - Autowiring, Annotations, Java based Configuration - slides
Spring - Part 2 - Autowiring, Annotations, Java based Configuration - slidesSpring - Part 2 - Autowiring, Annotations, Java based Configuration - slides
Spring - Part 2 - Autowiring, Annotations, Java based Configuration - slides
 
Js: master prototypes
Js: master prototypesJs: master prototypes
Js: master prototypes
 
Smooth scrolling in UITableView and UICollectionView
Smooth scrolling in UITableView and UICollectionViewSmooth scrolling in UITableView and UICollectionView
Smooth scrolling in UITableView and UICollectionView
 
Exception handling in plsql
Exception handling in plsqlException handling in plsql
Exception handling in plsql
 
Collectors in the Wild
Collectors in the WildCollectors in the Wild
Collectors in the Wild
 
Python lambda functions with filter, map & reduce function
Python lambda functions with filter, map & reduce functionPython lambda functions with filter, map & reduce function
Python lambda functions with filter, map & reduce function
 
PHP Form Validation Technique
PHP Form Validation TechniquePHP Form Validation Technique
PHP Form Validation Technique
 
slingmodels
slingmodelsslingmodels
slingmodels
 
Python Datatypes by SujithKumar
Python Datatypes by SujithKumarPython Datatypes by SujithKumar
Python Datatypes by SujithKumar
 
Creating Views - oracle database
Creating Views - oracle databaseCreating Views - oracle database
Creating Views - oracle database
 
Parboiled explained
Parboiled explainedParboiled explained
Parboiled explained
 

Similar to C++ - Constructors,Destructors, Operator overloading and Type conversion

Unit ii
Unit iiUnit ii
Unit ii
snehaarao19
 
2CPP13 - Operator Overloading
2CPP13 - Operator Overloading2CPP13 - Operator Overloading
2CPP13 - Operator Overloading
Michael Heron
 
constructor.ppt
constructor.pptconstructor.ppt
constructor.ppt
nivedita murugan
 
c++ UNIT II.pptx
c++ UNIT II.pptxc++ UNIT II.pptx
object oriented programming language.pptx
object oriented programming language.pptxobject oriented programming language.pptx
object oriented programming language.pptx
syedabbas594247
 
C++ training
C++ training C++ training
C++ training
PL Sharma
 
Constructor and destructor
Constructor and destructorConstructor and destructor
Constructor and destructor
rajshreemuthiah
 
Intro To C++ - Class #19: Functions
Intro To C++ - Class #19: FunctionsIntro To C++ - Class #19: Functions
Intro To C++ - Class #19: Functions
Blue Elephant Consulting
 
[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
Muhammad Hammad Waseem
 
Function different types of funtion
Function different types of funtionFunction different types of funtion
Function different types of funtion
svishalsingh01
 
Unit3_OOP-converted.pdf
Unit3_OOP-converted.pdfUnit3_OOP-converted.pdf
Unit3_OOP-converted.pdf
PowerfullBoy1
 
Learn c++ Programming Language
Learn c++ Programming LanguageLearn c++ Programming Language
Learn c++ Programming Language
Steve Johnson
 
2CPP04 - Objects and Classes
2CPP04 - Objects and Classes2CPP04 - Objects and Classes
2CPP04 - Objects and Classes
Michael Heron
 
Functions in c
Functions in cFunctions in c
Functions in c
sunila tharagaturi
 
Polymorphism
PolymorphismPolymorphism
Polymorphism
prabhat kumar
 
B.sc CSIT 2nd semester C++ Unit4
B.sc CSIT  2nd semester C++ Unit4B.sc CSIT  2nd semester C++ Unit4
B.sc CSIT 2nd semester C++ Unit4
Tekendra Nath Yogi
 
Object Oriented Design and Programming Unit-02
Object Oriented Design and Programming Unit-02Object Oriented Design and Programming Unit-02
Object Oriented Design and Programming Unit-02
sivakumarmcs
 

Similar to C++ - Constructors,Destructors, Operator overloading and Type conversion (20)

Unit ii
Unit iiUnit ii
Unit ii
 
2CPP13 - Operator Overloading
2CPP13 - Operator Overloading2CPP13 - Operator Overloading
2CPP13 - Operator Overloading
 
constructor.ppt
constructor.pptconstructor.ppt
constructor.ppt
 
c++ UNIT II.pptx
c++ UNIT II.pptxc++ UNIT II.pptx
c++ UNIT II.pptx
 
106da session5 c++
106da session5 c++106da session5 c++
106da session5 c++
 
object oriented programming language.pptx
object oriented programming language.pptxobject oriented programming language.pptx
object oriented programming language.pptx
 
C++ training
C++ training C++ training
C++ training
 
Constructor and destructor
Constructor and destructorConstructor and destructor
Constructor and destructor
 
Intro To C++ - Class #19: Functions
Intro To C++ - Class #19: FunctionsIntro To C++ - Class #19: Functions
Intro To C++ - Class #19: Functions
 
[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
 
3d7b7 session4 c++
3d7b7 session4 c++3d7b7 session4 c++
3d7b7 session4 c++
 
Function different types of funtion
Function different types of funtionFunction different types of funtion
Function different types of funtion
 
Unit3_OOP-converted.pdf
Unit3_OOP-converted.pdfUnit3_OOP-converted.pdf
Unit3_OOP-converted.pdf
 
Learn c++ Programming Language
Learn c++ Programming LanguageLearn c++ Programming Language
Learn c++ Programming Language
 
Classes and objects
Classes and objectsClasses and objects
Classes and objects
 
2CPP04 - Objects and Classes
2CPP04 - Objects and Classes2CPP04 - Objects and Classes
2CPP04 - Objects and Classes
 
Functions in c
Functions in cFunctions in c
Functions in c
 
Polymorphism
PolymorphismPolymorphism
Polymorphism
 
B.sc CSIT 2nd semester C++ Unit4
B.sc CSIT  2nd semester C++ Unit4B.sc CSIT  2nd semester C++ Unit4
B.sc CSIT 2nd semester C++ Unit4
 
Object Oriented Design and Programming Unit-02
Object Oriented Design and Programming Unit-02Object Oriented Design and Programming Unit-02
Object Oriented Design and Programming Unit-02
 

Recently uploaded

aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
siemaillard
 
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXXPhrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
MIRIAMSALINAS13
 
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Thiyagu K
 
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
MysoreMuleSoftMeetup
 
2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...
Sandy Millin
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
Thiyagu K
 
The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
Vivekanand Anglo Vedic Academy
 
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptxStudents, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
EduSkills OECD
 
Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345
beazzy04
 
PART A. Introduction to Costumer Service
PART A. Introduction to Costumer ServicePART A. Introduction to Costumer Service
PART A. Introduction to Costumer Service
PedroFerreira53928
 
How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17
Celine George
 
Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
DeeptiGupta154
 
special B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdfspecial B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdf
Special education needs
 
Ethnobotany and Ethnopharmacology ......
Ethnobotany and Ethnopharmacology ......Ethnobotany and Ethnopharmacology ......
Ethnobotany and Ethnopharmacology ......
Ashokrao Mane college of Pharmacy Peth-Vadgaon
 
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCECLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
BhavyaRajput3
 
Digital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and ResearchDigital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and Research
Vikramjit Singh
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
Jisc
 
Template Jadual Bertugas Kelas (Boleh Edit)
Template Jadual Bertugas Kelas (Boleh Edit)Template Jadual Bertugas Kelas (Boleh Edit)
Template Jadual Bertugas Kelas (Boleh Edit)
rosedainty
 
The Art Pastor's Guide to Sabbath | Steve Thomason
The Art Pastor's Guide to Sabbath | Steve ThomasonThe Art Pastor's Guide to Sabbath | Steve Thomason
The Art Pastor's Guide to Sabbath | Steve Thomason
Steve Thomason
 
Home assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdfHome assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdf
Tamralipta Mahavidyalaya
 

Recently uploaded (20)

aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
 
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXXPhrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
 
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
 
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
 
2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
 
The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
 
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptxStudents, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
 
Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345
 
PART A. Introduction to Costumer Service
PART A. Introduction to Costumer ServicePART A. Introduction to Costumer Service
PART A. Introduction to Costumer Service
 
How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17
 
Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
 
special B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdfspecial B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdf
 
Ethnobotany and Ethnopharmacology ......
Ethnobotany and Ethnopharmacology ......Ethnobotany and Ethnopharmacology ......
Ethnobotany and Ethnopharmacology ......
 
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCECLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
 
Digital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and ResearchDigital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and Research
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
 
Template Jadual Bertugas Kelas (Boleh Edit)
Template Jadual Bertugas Kelas (Boleh Edit)Template Jadual Bertugas Kelas (Boleh Edit)
Template Jadual Bertugas Kelas (Boleh Edit)
 
The Art Pastor's Guide to Sabbath | Steve Thomason
The Art Pastor's Guide to Sabbath | Steve ThomasonThe Art Pastor's Guide to Sabbath | Steve Thomason
The Art Pastor's Guide to Sabbath | Steve Thomason
 
Home assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdfHome assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdf
 

C++ - Constructors,Destructors, Operator overloading and Type conversion

  • 2. Introduction • A constructor in C++ is a special method that is automatically called when an object of a class is created. • To create a constructor, use the same name as the class, followed by parentheses.
  • 3. Constructors • A constructor is a special member function which enables an object to initialize itself when it is created. (In other word, it is used to initialize all class data members.) • It is special because its name is same as the class name. • In C++, Constructor is automatically called when object create. • These constructors get invoked whenever an object of its associated class is created. • It is called constructor because it constructs the values of data members of the class.
  • 4. Constructor- example class add { int m, n ; public : add (void) ; ------ }; add :: add (void) { m = 0; n = 0; } • When a class contains a constructor, it is guaranteed that an object created by the class will be initialized automatically. • add a ; • Not only creates the object a of type add but also initializes its data members m and n to zero. continue …
  • 5. Constructors • There is no need to write any statement to invoke the constructor function. • If a ‘normal’ member function is defined for zero initialization, we would need to invoke this function for each of the objects separately. • A constructor that accepts no parameters is called the default constructor. • The default constructor for class A is A : : A ( ) continue …
  • 6. Characteristics of Constructors • They should be declared in the public section. • They are invoked automatically when the objects are created. • They do not have return types, not even void and they cannot return values. continue …
  • 7. Characteristics of Constructors • They cannot be inherited, though a derived class can call the base class constructor. • Like other C++ functions, Constructors can have default arguments. • Constructors can not be virtual. continue …
  • 8. Characteristics of Constructors • We can not refer to their addresses. • An object with a constructor (or destructor) can not be used as a member of a union. • They make ‘implicit calls’ to the operators new and delete when memory allocation is required. continue …
  • 9.
  • 10. 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.
  • 11. #include <iostream> 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; } };
  • 12. int main() { // Constructor called Point p1(10, 15); // Access values assigned by constructor cout << "p1.x = " << p1.getX() << ", p1.y = " << p1.getY(); return 0; }
  • 13. Copy Constructor • A copy constructor is used to declare and initialize an object from another object. integer (integer & i) ; (to get value from other constructor) integer I 2 ( I 1 ) ; or integer I 2 = I 1 ; The process of initializing through a copy constructor is known as copy initialization.
  • 14. Copy Constructor • The statement I 2 = I 1; will not invoke the copy constructor. • If I 1 and I 2 are objects, this statement is legal and assigns the values of I 1 to I 2, member-by-member. • A reference variable has been used as an argument to the copy constructor. • We cannot pass the argument by value to a copy constructor. continue …
  • 15. Dynamic Constructors • The constructors can also be used to allocate memory while creating objects. • This will enable the system to allocate the right amount of memory for each object when the objects are not of the same size. • Allocation of memory to objects at the time of their construction is known as dynamic construction of objects. • The memory is created with the help of the new operator.
  • 16. Destructors • A destructor is used to destroy the objects that have been created by a constructor. • Like constructor, the destructor is a member function whose name is the same as the class name but is preceded by a tilde. eg: ~ integer ( ) { } • A destructor never takes any argument nor does it return any value. • It will be invoked implicitly by the compiler upon exit from the program – or block or function as the case may be – to clean up storage that is no longer accessible.
  • 17. Destructors • It is a good practice to declare destructors in a program since it releases memory space for further use. • Whenever new is used to allocate memory in the constructor, we should use delete to free that memory. continue …
  • 19. Introduction • It is one of the many exciting features of C++. • C++ has ability to provide the operators with a special meaning for a data types. • We can overload (give additional meaning to) all the C++ operators except: • Class member access operators ( . & .*) • Scope resolution operators ( : : ) • Size operator (sizeof) • Conditional operators (? : ) • When an operator is overloaded, its original meaning is not lost
  • 20. Defining Operator Overloading • To define an additional task to an operator, we must specify what it means in relation to the class to which the operator is applied. • This is done with the help of a special function called operator function. return type class-name : :operator op (arg-list) { Function body // task defined }
  • 21. DefiningOperatorOverloading • return type is the type of value returned by the specified operation. • op is the operator being overloaded. • op is preceded by the keyword operator. • operator op is the function name. continue…
  • 22. DefiningOperatorOverloading • Operator Function must be either member function (non-static) Or friend function. The basic difference : • A friend function will have only one argument for unary operators and two for binary operators. • A member function has no arguments for unary operators and one argument for binary operators. • Arguments may be passed either by value or by reference. continue…
  • 23. Process of OperatorOverloading The process of overloading involves the following steps: • Create a class that defines the data type that is to be used in the overloading operation. • Declare the operator function operator op( ) in the public part of the class. It may be either a member function or a friend function. • Define the operator function to implement the required operations. continue…
  • 24. Process of OperatorOverloading • Overloaded operator functions can be invoked by expressions such as: For unary operators: op x or x op For binary operators: x op y • op x or x op would be interpreted as for a friend function:operator op (x) for a member function: x.operator op ( ) • x op y would be interpreted as for a friend function:operator op (x,y) for a member function: x.operator op (y) continue…
  • 25. Overloading Unary Operators Consider a unary minus operator: • It takes just one operand. • It changes the sign of an operand when applied to a basic data item. • The unary minus when applied to an object should change the sign of each of its data items.
  • 26. Overloading Binary Operators As a rule, in overloading binary operators, • the left-hand operand is used to invoke the operator function and • the right-hand operand is passed as an argument.
  • 27. Overloading Binary Operators complex operator+(complex a, complex b) { return complex((a.x + b.x),(a.y + b.y)); } • The compiler invokes an appropriate constructor, initializes an object with no name and returns the contents for copying into an object. • Such an object is called a temporary object. continue…
  • 28. Overloading Binary Operators Using Friends • Friend function requires two arguments to be explicitly passes to it. • Member function requires only one. friend complex operator+(complex, complex); complex operator+(complex a, complex b) { return complex((a.x + b.x),(a.y + b.y)); } • We can use a friend function with built-in type data as the left- hand operand and an object as the right-hand operand.
  • 29. Manipulation of Strings using Operators • There are lot of limitations in string manipulation in C as well as in C++. • Implementation of strings require character arrays, pointers and string functions. • C++ permits us to create our own definitions of operators that can be used to manipulate the strings very much similar to other built- in data types. • ANSI C++ committee has added a new class called string to the C++ class library that supports all kinds of string manipulations.
  • 30. Manipulationof Strings using Operators • Strings can be defined as class, objects which can be then manipulated like the built-in types. • Since the strings vary in size, we use new to allocate memory for each string and a pointer variable to point to the string array. continue…
  • 31. Manipulationof Strings using Operators • We must create string objects that can hold two pieces of information: • Length • Location class string { char *p; // pointer to string int len; // length of string public : ------ ------ }; continue…
  • 32. Rules For Overloading Operators • Only existing operators can be overloaded. New operators cannot be created. • The overloaded operator must have at least one operand that is of user-defined type. • We cannot change the basic meaning of an operator. • Overloaded operators follow the syntax rules of the original operators.
  • 33. Rules ForOverloadingOperators • The following operators that cannot be overloaded: Size of Size of operator . Membership operator .* Pointer-to-member operator : : Scope resolution operator ? ; Conditional operator continue…
  • 34. Rules ForOverloadingOperators • The following operators can be over loaded with the use of member functions and not by the use of friend functions: • Assignment operator = • Function call operator( ) • Subscripting operator [ ] • Class member access operator -> • Unary operators, overloaded by means of a member function, take no explicit arguments and return no explicit values, but, those overloaded by means of a friend function, take one reference argument. continue…
  • 35. Rules ForOverloadingOperators • Binary arithmetic operators such as +, -, * and / must explicitly return a value. They must not attempt to change their own arguments. • Binary operators overloaded through a member function take one explicit argument and those which are overloaded through a friend function take two explicit arguments. continue…
  • 36. Type Conversions • The type conversions are automatic only when the data types involved are built-in types. int m; float x = 3.14159; m = x; // convert x to integer before its value is assigned // to m. • For user defined data types, the compiler does not support automatic type conversions. • We must design the conversion routines by ourselves.
  • 37. Type Conversions • Different situations of data conversion between incompatible types. • Conversion from basic type to class type. • Conversion from class type to basic type. • Conversion from one class type to another class type. continue…
  • 38. Basic to ClassType • A constructor to build a string type object from a char * type variable. string : : string(char *a) { length = strlen(a); P = new char[length+1]; strcpy(P,a); } • The variables length and p are data members of the class string. continue…
  • 39. Basic to ClassType class time { int hrs ; int mins ; public : … time (int t) { hrs = t / 60 ; mins = t % 60; } } ; time T1; int duration = 85; T1 = duration; continue…
  • 40. ClassTo BasicType • A constructor function do not support type conversion from a class type to a basic type. • An overloaded casting operator is used to convert a class type data to a basic type. • It is also referred to as conversion function. operator typename( ) { … … ( function statements ) … } • This function converts a calss type data to typename. continue…
  • 41. ClassTo BasicType vector : : operator double( ) { double sum = 0; for (int i=0; i < size ; i++) sum = sum + v[i] * v[i]; return sqrt (sum); } • This function converts a vector to the square root of the sum of squares of its components. continue…
  • 42. ClassTo BasicType • The casting operator function should satisfy the following conditions: • It must be a class member. • It must not specify a return type. • It must not have any arguments. vector : : operator double( ) { double sum = 0; for (int i=0; i < size ; i++) sum = sum + v[i] * v[i]; return sqrt (sum); } continue…
  • 43. ClassTo BasicType • Conversion functions are member functions and it is invoked with objects. • Therefore the values used for conversion inside the function belong to the object that invoked the function. • This means that the function does not need an argument. continue…
  • 44. One Class ToAnother Class Type objX = objY ; // objects of different types • objX is an object of class X and objY is an object of class Y. • The class Y type data is converted to the class X type data and the converted value is assigned to the objX. • Conversion is takes place from class Y to class X. • Y is known as source class. • X is known as destination class.
  • 45. One ClassToAnotherClassType • Conversion between objects of different classes can be carried out by either a constructor or a conversion function. • Choosing of constructor or the conversion function depends upon where we want the type-conversion function to be located in the source class or in the destination class. continue…
  • 46. One ClassToAnotherClassType operator typename( ) • Converts the class object of which it is a member to typename. • The typename may be a built-in type or a user-defined one. • In the case of conversions between objects, typename refers to the destination class. • When a class needs to be converted, a casting operator function can be used at the source class. • The conversion takes place in the source class and the result is given to the destination class object. continue…
  • 47. One ClassToAnotherClassType Consider a constructor function with a single argument • Construction function will be a member of the destination class. • The argument belongs to the source class and is passed to the destination class for conversion. • The conversion constructor be placed in the destination class. continue…