SlideShare una empresa de Scribd logo
1 de 28
CONSTRUCTOR & DESTRUCTOR
Chap 61
By:-GouravKottawar
CONTENTS
6.1 Constructor
6.2 Parameterized Constructor
6.3 Multiple Constructor in a Class
6.4 Constructors with Default Arguments
6.5 Dynamic Initialization of Objects
6.6 Copy Constructor
6.7 Dynamic Constructor
6.8 Const Object
6.9 Destructor
2
By:-GouravKottawar
CONSTRUCTORS
 A constructor is a special member function whose
task is to initialize the objects of its class.
 It is special because its name is same as the class
name.
 The constructor is 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.
3
By:-GouravKottawar
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.
4
By:-GouravKottawar
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 …
5
By:-GouravKottawar
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.
6
By:-GouravKottawar
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 …
7
By:-GouravKottawar
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 …
8
By:-GouravKottawar
CONSTRUCTORS
 When a constructor is declared for a class
initialization of the class objects becomes mandatory.
continue …
9
By:-GouravKottawar
PARAMETERIZED CONSTRUCTORS
 It may be necessary to initialize the various data
elements of different objects with different values
when they are created.
 This is achieved by passing arguments to the
constructor function when the objects are created.
 The constructors that can take arguments are called
parameterized constructors.
10
By:-GouravKottawar
PARAMETERIZED CONSTRUCTORS
class add
{
int m, n ;
public :
add (int, int) ;
------
};
add : : add (int x, int y)
{
m = x; n = y;
}
 When a constructor is
parameterized, we must pass
the initial values as
arguments to the constructor
function when an object is
declared.
 Two ways Calling:
o Explicit
 add sum = add(2,3);
o Implicit
 add sum(2,3)
 Shorthand method
continue …
11
By:-GouravKottawar
MULTIPLE CONSTRUCTORS IN A CLASS
 C + + permits to use more than one constructors in
a single class.
 Add( ) ; // No arguments
 Add (int, int) ; // Two arguments
12
By:-GouravKottawar
MULTIPLE CONSTRUCTORS IN A CLASS
class add
{
int m, n ;
public :
add ( ) {m = 0 ; n = 0 ;}
add (int a, int b)
{m = a ; n = b ;}
add (add & i)
{m = i.m ; n = i.n ;}
};
 The first constructor receives
no arguments.
 The second constructor
receives two integer
arguments.
 The third constructor receives
one add object as an
argument.
continue …
13
By:-GouravKottawar
MULTIPLE CONSTRUCTORS IN A CLASS
class add
{
int m, n ;
public :
add ( ) {m = 0 ; n = 0
;}
add (int a, int b)
{m = a ; n = b ;}
add (add & i)
{m = i.m ; n = i.n
;}
};
 Add a1;
 Would automatically
invoke the first constructor
and set both m and n of a1
to zero.
 Add a2(10,20);
 Would call the second
constructor which will
initialize the data members
m and n of a2 to 10 and 20
respectively.
continue …
14
By:-GouravKottawar
MULTIPLE CONSTRUCTORS IN A CLASS
class add
{
int m, n ;
public :
add ( ) {m = 0 ; n = 0
;}
add (int a, int b)
{m = a ; n = b ;}
add (add & i)
{m = i.m ; n = i.n
;}
};
 Add a3(a2);
 Would invoke the third
constructor which copies
the values of a2 into a3.
 This type of constructor is
called the “copy
constructor”.
 Construction Overloading
 More than one constructor
function is defined in a
class.
continue …
15
By:-GouravKottawar
MULTIPLE CONSTRUCTORS IN A CLASS
class complex
{
float x, y ;
public :
complex ( ) { }
complex (float a)
{ x = y = a ; }
complex (float r, float i)
{ x = r ; y = i }
------
};
 complex ( ) { }
 This contains the empty
body and does not do
anything.
 This is used to create
objects without any initial
values.
continue …
16
By:-GouravKottawar
MULTIPLE CONSTRUCTORS IN A CLASS
 C + + compiler has an implicit constructor which
creates objects, even though it was not defined in
the class.
 This works well as long as we do not use any other
constructor in the class.
 However, once we define a constructor, we must
also define the “do-nothing” implicit constructor.
continue …
17
By:-GouravKottawar
CONSTRUCTORS WITH DEFAULT
ARGUMENTS
 It is possible to define constructors with default
arguments.
 Consider complex (float real, float imag = 0);
 The default value of the argument imag is zero.
 complex C1 (5.0) assigns the value 5.0 to the real
variable and 0.0 to imag.
 complex C2(2.0,3.0) assigns the value 2.0 to real and
3.0 to imag.
18
By:-GouravKottawar
CONSTRUCTORS WITH DEFAULT
ARGUMENTS
 A : : A ( )  Default constructor
 A : : A (int = 0)  Default argument
constructor
 The default argument constructor can be called with
either one argument or no arguments.
 When called with no arguments, it becomes a
default constructor.
continue …
19
By:-GouravKottawar
DYNAMIC INITIALIZATION OF OBJECTS
 Providing initial value to objects at run time.
 Advantage – We can provide various
initialization
formats, using overloaded
constructors.
This provides the flexibility of using
different format of data at run time
depending upon the situation.
20
By:-GouravKottawar
COPY CONSTRUCTOR
A copy constructor is used to declare and initialize an
object from another object.
integer (integer & i) ;
integer I 2 ( I 1 ) ; or integer I 2 = I 1 ;
The process of initializing through a copy constructor is
known as copy initialization.
21
By:-GouravKottawar
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.
continue …
22
By:-GouravKottawar
COPY CONSTRUCTOR
 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 …
23
By:-GouravKottawar
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.
24
By:-GouravKottawar
DYNAMIC CONSTRUCTORS
 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.
continue …
25
By:-GouravKottawar
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 ( ) { }
26
By:-GouravKottawar
DESTRUCTORS
 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.
continue …
27
By:-GouravKottawar
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 …
28
By:-GouravKottawar

Más contenido relacionado

La actualidad más candente

Abstraction in c++ and Real Life Example of Abstraction in C++
Abstraction in c++ and Real Life Example of Abstraction in C++Abstraction in c++ and Real Life Example of Abstraction in C++
Abstraction in c++ and Real Life Example of Abstraction in C++Hitesh Kumar
 
chapter-9-constructors.pdf
chapter-9-constructors.pdfchapter-9-constructors.pdf
chapter-9-constructors.pdfstudy material
 
C++ Pointers And References
C++ Pointers And ReferencesC++ Pointers And References
C++ Pointers And Referencesverisan
 
Constructor overloading in C++
Constructor overloading in C++Constructor overloading in C++
Constructor overloading in C++Learn By Watch
 
Moore and mealy machines
Moore and mealy machinesMoore and mealy machines
Moore and mealy machineslavishka_anuj
 
Easy Steps to implement UDP Server and Client Sockets
Easy Steps to implement UDP Server and Client SocketsEasy Steps to implement UDP Server and Client Sockets
Easy Steps to implement UDP Server and Client Socketsbabak danyal
 
Looping Statements and Control Statements in Python
Looping Statements and Control Statements in PythonLooping Statements and Control Statements in Python
Looping Statements and Control Statements in PythonPriyankaC44
 
Constructors and destructors
Constructors and destructorsConstructors and destructors
Constructors and destructorsNilesh Dalvi
 
Inline function in C++
Inline function in C++Inline function in C++
Inline function in C++Learn By Watch
 
Dynamic Memory Allocation, Pointers and Functions, Pointers and Structures
Dynamic Memory Allocation, Pointers and Functions, Pointers and StructuresDynamic Memory Allocation, Pointers and Functions, Pointers and Structures
Dynamic Memory Allocation, Pointers and Functions, Pointers and StructuresSelvaraj Seerangan
 
primitive data types
 primitive data types primitive data types
primitive data typesJadavsejal
 
Unit 9. Structure and Unions
Unit 9. Structure and UnionsUnit 9. Structure and Unions
Unit 9. Structure and UnionsAshim Lamichhane
 

La actualidad más candente (20)

Abstraction in c++ and Real Life Example of Abstraction in C++
Abstraction in c++ and Real Life Example of Abstraction in C++Abstraction in c++ and Real Life Example of Abstraction in C++
Abstraction in c++ and Real Life Example of Abstraction in C++
 
chapter-9-constructors.pdf
chapter-9-constructors.pdfchapter-9-constructors.pdf
chapter-9-constructors.pdf
 
C++ Pointers And References
C++ Pointers And ReferencesC++ Pointers And References
C++ Pointers And References
 
Constructor overloading in C++
Constructor overloading in C++Constructor overloading in C++
Constructor overloading in C++
 
pointer-to-object-.pptx
pointer-to-object-.pptxpointer-to-object-.pptx
pointer-to-object-.pptx
 
Combinational circuit
Combinational circuitCombinational circuit
Combinational circuit
 
Pointers
PointersPointers
Pointers
 
Moore and mealy machines
Moore and mealy machinesMoore and mealy machines
Moore and mealy machines
 
Array in c++
Array in c++Array in c++
Array in c++
 
Easy Steps to implement UDP Server and Client Sockets
Easy Steps to implement UDP Server and Client SocketsEasy Steps to implement UDP Server and Client Sockets
Easy Steps to implement UDP Server and Client Sockets
 
Looping Statements and Control Statements in Python
Looping Statements and Control Statements in PythonLooping Statements and Control Statements in Python
Looping Statements and Control Statements in Python
 
Constructors and destructors
Constructors and destructorsConstructors and destructors
Constructors and destructors
 
Oop concepts in python
Oop concepts in pythonOop concepts in python
Oop concepts in python
 
Inline function in C++
Inline function in C++Inline function in C++
Inline function in C++
 
Dynamic Memory Allocation, Pointers and Functions, Pointers and Structures
Dynamic Memory Allocation, Pointers and Functions, Pointers and StructuresDynamic Memory Allocation, Pointers and Functions, Pointers and Structures
Dynamic Memory Allocation, Pointers and Functions, Pointers and Structures
 
Constructor ppt
Constructor pptConstructor ppt
Constructor ppt
 
Iterator
IteratorIterator
Iterator
 
primitive data types
 primitive data types primitive data types
primitive data types
 
Unit 9. Structure and Unions
Unit 9. Structure and UnionsUnit 9. Structure and Unions
Unit 9. Structure and Unions
 
C++ string
C++ stringC++ string
C++ string
 

Destacado

Constructor and Destructor PPT
Constructor and Destructor PPTConstructor and Destructor PPT
Constructor and Destructor PPTShubham Mondal
 
Constructor and destructor in c++
Constructor and destructor in c++Constructor and destructor in c++
Constructor and destructor in c++Learn By Watch
 
04. constructor & destructor
04. constructor & destructor04. constructor & destructor
04. constructor & destructorHaresh Jaiswal
 
Constructor and Destructor
Constructor and DestructorConstructor and Destructor
Constructor and DestructorKamal Acharya
 
01. introduction to C++
01. introduction to C++01. introduction to C++
01. introduction to C++Haresh Jaiswal
 
constructor with default arguments and dynamic initialization of objects
constructor with default arguments and dynamic initialization of objectsconstructor with default arguments and dynamic initialization of objects
constructor with default arguments and dynamic initialization of objectsKanhaiya Saxena
 
Java Static Factory Methods
Java Static Factory MethodsJava Static Factory Methods
Java Static Factory MethodsYe Win
 
New operator and methods.15
New operator and methods.15New operator and methods.15
New operator and methods.15myrajendra
 
Constructor and desturctor
Constructor and desturctorConstructor and desturctor
Constructor and desturctorSomnath Kulkarni
 
Builder pattern vs constructor
Builder pattern vs constructorBuilder pattern vs constructor
Builder pattern vs constructorLiviu Tudor
 

Destacado (20)

Constructors & destructors
Constructors & destructorsConstructors & destructors
Constructors & destructors
 
Constructor and Destructor PPT
Constructor and Destructor PPTConstructor and Destructor PPT
Constructor and Destructor PPT
 
Constructor and destructor in c++
Constructor and destructor in c++Constructor and destructor in c++
Constructor and destructor in c++
 
Constructors and Destructors
Constructors and DestructorsConstructors and Destructors
Constructors and Destructors
 
Constructor and destructor
Constructor  and  destructor Constructor  and  destructor
Constructor and destructor
 
04. constructor & destructor
04. constructor & destructor04. constructor & destructor
04. constructor & destructor
 
Constructor & Destructor
Constructor & DestructorConstructor & Destructor
Constructor & Destructor
 
Constructor and Destructor
Constructor and DestructorConstructor and Destructor
Constructor and Destructor
 
01. introduction to C++
01. introduction to C++01. introduction to C++
01. introduction to C++
 
constructor with default arguments and dynamic initialization of objects
constructor with default arguments and dynamic initialization of objectsconstructor with default arguments and dynamic initialization of objects
constructor with default arguments and dynamic initialization of objects
 
03. oop concepts
03. oop concepts03. oop concepts
03. oop concepts
 
File system implementation
File system implementationFile system implementation
File system implementation
 
File System Implementation
File System ImplementationFile System Implementation
File System Implementation
 
Constructor in java
Constructor in javaConstructor in java
Constructor in java
 
Java Static Factory Methods
Java Static Factory MethodsJava Static Factory Methods
Java Static Factory Methods
 
Classes and objects
Classes and objectsClasses and objects
Classes and objects
 
Chapter 2.datatypes and operators
Chapter 2.datatypes and operatorsChapter 2.datatypes and operators
Chapter 2.datatypes and operators
 
New operator and methods.15
New operator and methods.15New operator and methods.15
New operator and methods.15
 
Constructor and desturctor
Constructor and desturctorConstructor and desturctor
Constructor and desturctor
 
Builder pattern vs constructor
Builder pattern vs constructorBuilder pattern vs constructor
Builder pattern vs constructor
 

Similar a constructor & destructor in cpp

Constructors & Destructors [Compatibility Mode].pdf
Constructors & Destructors [Compatibility Mode].pdfConstructors & Destructors [Compatibility Mode].pdf
Constructors & Destructors [Compatibility Mode].pdfLadallaRajKumar
 
Constructors and destructors in C++
Constructors and destructors in  C++Constructors and destructors in  C++
Constructors and destructors in C++RAJ KUMAR
 
Constructor& destructor
Constructor& destructorConstructor& destructor
Constructor& destructorchauhankapil
 
Constructor and destructor
Constructor and destructorConstructor and destructor
Constructor and destructorrajshreemuthiah
 
ConsTRUCTION AND DESTRUCTION
ConsTRUCTION AND DESTRUCTIONConsTRUCTION AND DESTRUCTION
ConsTRUCTION AND DESTRUCTIONShweta Shah
 
C++ Unit-III Lecture-3a-C++ Programming Concepts
C++ Unit-III Lecture-3a-C++ Programming ConceptsC++ Unit-III Lecture-3a-C++ Programming Concepts
C++ Unit-III Lecture-3a-C++ Programming Conceptsdharawagh9999
 
CONSTRUCTORS IN C++ +2 COMPUTER SCIENCE
CONSTRUCTORS IN C++ +2 COMPUTER SCIENCECONSTRUCTORS IN C++ +2 COMPUTER SCIENCE
CONSTRUCTORS IN C++ +2 COMPUTER SCIENCEVenugopalavarma Raja
 
constructors and destructors
constructors and destructorsconstructors and destructors
constructors and destructorsAkshaya Parida
 
Constructors and Destructors
Constructors and DestructorsConstructors and Destructors
Constructors and DestructorsKeyur Vadodariya
 
Types of Constructor in C++
Types of Constructor in C++Types of Constructor in C++
Types of Constructor in C++Bhavik Vashi
 
vb.net Constructor and destructor
vb.net Constructor and destructorvb.net Constructor and destructor
vb.net Constructor and destructorsuraj pandey
 
Class notes(week 3) on class objects and methods
Class notes(week 3) on class objects and methodsClass notes(week 3) on class objects and methods
Class notes(week 3) on class objects and methodsKuntal Bhowmick
 
Class notes(week 3) on class objects and methods
Class notes(week 3) on class objects and methodsClass notes(week 3) on class objects and methods
Class notes(week 3) on class objects and methodsKuntal Bhowmick
 

Similar a constructor & destructor in cpp (20)

Constructors and destructors
Constructors and destructorsConstructors and destructors
Constructors and destructors
 
Constructors & Destructors [Compatibility Mode].pdf
Constructors & Destructors [Compatibility Mode].pdfConstructors & Destructors [Compatibility Mode].pdf
Constructors & Destructors [Compatibility Mode].pdf
 
Constructors and destructors in C++
Constructors and destructors in  C++Constructors and destructors in  C++
Constructors and destructors in C++
 
Constructor& destructor
Constructor& destructorConstructor& destructor
Constructor& destructor
 
Constructor,destructors cpp
Constructor,destructors cppConstructor,destructors cpp
Constructor,destructors cpp
 
constructor.ppt
constructor.pptconstructor.ppt
constructor.ppt
 
Constructor and destructor
Constructor and destructorConstructor and destructor
Constructor and destructor
 
Constructors destructors
Constructors destructorsConstructors destructors
Constructors destructors
 
ConsTRUCTION AND DESTRUCTION
ConsTRUCTION AND DESTRUCTIONConsTRUCTION AND DESTRUCTION
ConsTRUCTION AND DESTRUCTION
 
C++ Unit-III Lecture-3a-C++ Programming Concepts
C++ Unit-III Lecture-3a-C++ Programming ConceptsC++ Unit-III Lecture-3a-C++ Programming Concepts
C++ Unit-III Lecture-3a-C++ Programming Concepts
 
Constructors & Destructors
Constructors  & DestructorsConstructors  & Destructors
Constructors & Destructors
 
CONSTRUCTORS IN C++ +2 COMPUTER SCIENCE
CONSTRUCTORS IN C++ +2 COMPUTER SCIENCECONSTRUCTORS IN C++ +2 COMPUTER SCIENCE
CONSTRUCTORS IN C++ +2 COMPUTER SCIENCE
 
constructors and destructors
constructors and destructorsconstructors and destructors
constructors and destructors
 
Constructors and Destructors
Constructors and DestructorsConstructors and Destructors
Constructors and Destructors
 
Types of Constructor in C++
Types of Constructor in C++Types of Constructor in C++
Types of Constructor in C++
 
Constructors and Destructor in C++
Constructors and Destructor in C++Constructors and Destructor in C++
Constructors and Destructor in C++
 
vb.net Constructor and destructor
vb.net Constructor and destructorvb.net Constructor and destructor
vb.net Constructor and destructor
 
Class notes(week 3) on class objects and methods
Class notes(week 3) on class objects and methodsClass notes(week 3) on class objects and methods
Class notes(week 3) on class objects and methods
 
5 Constructors and Destructors
5 Constructors and Destructors5 Constructors and Destructors
5 Constructors and Destructors
 
Class notes(week 3) on class objects and methods
Class notes(week 3) on class objects and methodsClass notes(week 3) on class objects and methods
Class notes(week 3) on class objects and methods
 

Más de gourav kottawar

operator overloading & type conversion in cpp
operator overloading & type conversion in cppoperator overloading & type conversion in cpp
operator overloading & type conversion in cppgourav kottawar
 
classes & objects in cpp
classes & objects in cppclasses & objects in cpp
classes & objects in cppgourav kottawar
 
working file handling in cpp overview
working file handling in cpp overviewworking file handling in cpp overview
working file handling in cpp overviewgourav kottawar
 
pointers, virtual functions and polymorphisms in c++ || in cpp
pointers, virtual functions and polymorphisms in c++ || in cpppointers, virtual functions and polymorphisms in c++ || in cpp
pointers, virtual functions and polymorphisms in c++ || in cppgourav kottawar
 
exception handling in cpp
exception handling in cppexception handling in cpp
exception handling in cppgourav kottawar
 
cpp input & output system basics
cpp input & output system basicscpp input & output system basics
cpp input & output system basicsgourav kottawar
 
operator overloading & type conversion in cpp over view || c++
operator overloading & type conversion in cpp over view || c++operator overloading & type conversion in cpp over view || c++
operator overloading & type conversion in cpp over view || c++gourav kottawar
 
constructor & destructor in cpp
constructor & destructor in cppconstructor & destructor in cpp
constructor & destructor in cppgourav kottawar
 
classes & objects in cpp overview
classes & objects in cpp overviewclasses & objects in cpp overview
classes & objects in cpp overviewgourav kottawar
 
SQL || overview and detailed information about Sql
SQL || overview and detailed information about SqlSQL || overview and detailed information about Sql
SQL || overview and detailed information about Sqlgourav kottawar
 
SQL querys in detail || Sql query slides
SQL querys in detail || Sql query slidesSQL querys in detail || Sql query slides
SQL querys in detail || Sql query slidesgourav kottawar
 
Rrelational algebra in dbms overview
Rrelational algebra in dbms overviewRrelational algebra in dbms overview
Rrelational algebra in dbms overviewgourav kottawar
 
overview of database concept
overview of database conceptoverview of database concept
overview of database conceptgourav kottawar
 
Relational Model in dbms & sql database
Relational Model in dbms & sql databaseRelational Model in dbms & sql database
Relational Model in dbms & sql databasegourav kottawar
 
DBMS information in detail || Dbms (lab) ppt
DBMS information in detail || Dbms (lab) pptDBMS information in detail || Dbms (lab) ppt
DBMS information in detail || Dbms (lab) pptgourav kottawar
 
security and privacy in dbms and in sql database
security and privacy in dbms and in sql databasesecurity and privacy in dbms and in sql database
security and privacy in dbms and in sql databasegourav kottawar
 

Más de gourav kottawar (20)

operator overloading & type conversion in cpp
operator overloading & type conversion in cppoperator overloading & type conversion in cpp
operator overloading & type conversion in cpp
 
classes & objects in cpp
classes & objects in cppclasses & objects in cpp
classes & objects in cpp
 
expression in cpp
expression in cppexpression in cpp
expression in cpp
 
basics of c++
basics of c++basics of c++
basics of c++
 
working file handling in cpp overview
working file handling in cpp overviewworking file handling in cpp overview
working file handling in cpp overview
 
pointers, virtual functions and polymorphisms in c++ || in cpp
pointers, virtual functions and polymorphisms in c++ || in cpppointers, virtual functions and polymorphisms in c++ || in cpp
pointers, virtual functions and polymorphisms in c++ || in cpp
 
exception handling in cpp
exception handling in cppexception handling in cpp
exception handling in cpp
 
cpp input & output system basics
cpp input & output system basicscpp input & output system basics
cpp input & output system basics
 
operator overloading & type conversion in cpp over view || c++
operator overloading & type conversion in cpp over view || c++operator overloading & type conversion in cpp over view || c++
operator overloading & type conversion in cpp over view || c++
 
constructor & destructor in cpp
constructor & destructor in cppconstructor & destructor in cpp
constructor & destructor in cpp
 
basics of c++
basics of c++basics of c++
basics of c++
 
classes & objects in cpp overview
classes & objects in cpp overviewclasses & objects in cpp overview
classes & objects in cpp overview
 
expression in cpp
expression in cppexpression in cpp
expression in cpp
 
SQL || overview and detailed information about Sql
SQL || overview and detailed information about SqlSQL || overview and detailed information about Sql
SQL || overview and detailed information about Sql
 
SQL querys in detail || Sql query slides
SQL querys in detail || Sql query slidesSQL querys in detail || Sql query slides
SQL querys in detail || Sql query slides
 
Rrelational algebra in dbms overview
Rrelational algebra in dbms overviewRrelational algebra in dbms overview
Rrelational algebra in dbms overview
 
overview of database concept
overview of database conceptoverview of database concept
overview of database concept
 
Relational Model in dbms & sql database
Relational Model in dbms & sql databaseRelational Model in dbms & sql database
Relational Model in dbms & sql database
 
DBMS information in detail || Dbms (lab) ppt
DBMS information in detail || Dbms (lab) pptDBMS information in detail || Dbms (lab) ppt
DBMS information in detail || Dbms (lab) ppt
 
security and privacy in dbms and in sql database
security and privacy in dbms and in sql databasesecurity and privacy in dbms and in sql database
security and privacy in dbms and in sql database
 

Último

call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4MiaBumagat1
 
Science 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptxScience 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptxMaryGraceBautista27
 
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfVirtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfErwinPantujan2
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPCeline George
 
4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptxmary850239
 
ACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfSpandanaRallapalli
 
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfAMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfphamnguyenenglishnb
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPCeline George
 
Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Seán Kennedy
 
Choosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for ParentsChoosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for Parentsnavabharathschool99
 
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSJoshuaGantuangco2
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...Nguyen Thanh Tu Collection
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 

Último (20)

YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptxYOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4
 
Science 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptxScience 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptx
 
Raw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptxRaw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptx
 
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfVirtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERP
 
4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx
 
ACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdf
 
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfAMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERP
 
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptxFINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
 
Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...
 
Choosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for ParentsChoosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for Parents
 
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptxYOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 

constructor & destructor in cpp

  • 1. CONSTRUCTOR & DESTRUCTOR Chap 61 By:-GouravKottawar
  • 2. CONTENTS 6.1 Constructor 6.2 Parameterized Constructor 6.3 Multiple Constructor in a Class 6.4 Constructors with Default Arguments 6.5 Dynamic Initialization of Objects 6.6 Copy Constructor 6.7 Dynamic Constructor 6.8 Const Object 6.9 Destructor 2 By:-GouravKottawar
  • 3. CONSTRUCTORS  A constructor is a special member function whose task is to initialize the objects of its class.  It is special because its name is same as the class name.  The constructor is 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. 3 By:-GouravKottawar
  • 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. 4 By:-GouravKottawar
  • 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 … 5 By:-GouravKottawar
  • 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. 6 By:-GouravKottawar
  • 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 … 7 By:-GouravKottawar
  • 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 … 8 By:-GouravKottawar
  • 9. CONSTRUCTORS  When a constructor is declared for a class initialization of the class objects becomes mandatory. continue … 9 By:-GouravKottawar
  • 10. PARAMETERIZED CONSTRUCTORS  It may be necessary to initialize the various data elements of different objects with different values when they are created.  This is achieved by passing arguments to the constructor function when the objects are created.  The constructors that can take arguments are called parameterized constructors. 10 By:-GouravKottawar
  • 11. PARAMETERIZED CONSTRUCTORS class add { int m, n ; public : add (int, int) ; ------ }; add : : add (int x, int y) { m = x; n = y; }  When a constructor is parameterized, we must pass the initial values as arguments to the constructor function when an object is declared.  Two ways Calling: o Explicit  add sum = add(2,3); o Implicit  add sum(2,3)  Shorthand method continue … 11 By:-GouravKottawar
  • 12. MULTIPLE CONSTRUCTORS IN A CLASS  C + + permits to use more than one constructors in a single class.  Add( ) ; // No arguments  Add (int, int) ; // Two arguments 12 By:-GouravKottawar
  • 13. MULTIPLE CONSTRUCTORS IN A CLASS class add { int m, n ; public : add ( ) {m = 0 ; n = 0 ;} add (int a, int b) {m = a ; n = b ;} add (add & i) {m = i.m ; n = i.n ;} };  The first constructor receives no arguments.  The second constructor receives two integer arguments.  The third constructor receives one add object as an argument. continue … 13 By:-GouravKottawar
  • 14. MULTIPLE CONSTRUCTORS IN A CLASS class add { int m, n ; public : add ( ) {m = 0 ; n = 0 ;} add (int a, int b) {m = a ; n = b ;} add (add & i) {m = i.m ; n = i.n ;} };  Add a1;  Would automatically invoke the first constructor and set both m and n of a1 to zero.  Add a2(10,20);  Would call the second constructor which will initialize the data members m and n of a2 to 10 and 20 respectively. continue … 14 By:-GouravKottawar
  • 15. MULTIPLE CONSTRUCTORS IN A CLASS class add { int m, n ; public : add ( ) {m = 0 ; n = 0 ;} add (int a, int b) {m = a ; n = b ;} add (add & i) {m = i.m ; n = i.n ;} };  Add a3(a2);  Would invoke the third constructor which copies the values of a2 into a3.  This type of constructor is called the “copy constructor”.  Construction Overloading  More than one constructor function is defined in a class. continue … 15 By:-GouravKottawar
  • 16. MULTIPLE CONSTRUCTORS IN A CLASS class complex { float x, y ; public : complex ( ) { } complex (float a) { x = y = a ; } complex (float r, float i) { x = r ; y = i } ------ };  complex ( ) { }  This contains the empty body and does not do anything.  This is used to create objects without any initial values. continue … 16 By:-GouravKottawar
  • 17. MULTIPLE CONSTRUCTORS IN A CLASS  C + + compiler has an implicit constructor which creates objects, even though it was not defined in the class.  This works well as long as we do not use any other constructor in the class.  However, once we define a constructor, we must also define the “do-nothing” implicit constructor. continue … 17 By:-GouravKottawar
  • 18. CONSTRUCTORS WITH DEFAULT ARGUMENTS  It is possible to define constructors with default arguments.  Consider complex (float real, float imag = 0);  The default value of the argument imag is zero.  complex C1 (5.0) assigns the value 5.0 to the real variable and 0.0 to imag.  complex C2(2.0,3.0) assigns the value 2.0 to real and 3.0 to imag. 18 By:-GouravKottawar
  • 19. CONSTRUCTORS WITH DEFAULT ARGUMENTS  A : : A ( )  Default constructor  A : : A (int = 0)  Default argument constructor  The default argument constructor can be called with either one argument or no arguments.  When called with no arguments, it becomes a default constructor. continue … 19 By:-GouravKottawar
  • 20. DYNAMIC INITIALIZATION OF OBJECTS  Providing initial value to objects at run time.  Advantage – We can provide various initialization formats, using overloaded constructors. This provides the flexibility of using different format of data at run time depending upon the situation. 20 By:-GouravKottawar
  • 21. COPY CONSTRUCTOR A copy constructor is used to declare and initialize an object from another object. integer (integer & i) ; integer I 2 ( I 1 ) ; or integer I 2 = I 1 ; The process of initializing through a copy constructor is known as copy initialization. 21 By:-GouravKottawar
  • 22. 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. continue … 22 By:-GouravKottawar
  • 23. COPY CONSTRUCTOR  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 … 23 By:-GouravKottawar
  • 24. 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. 24 By:-GouravKottawar
  • 25. DYNAMIC CONSTRUCTORS  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. continue … 25 By:-GouravKottawar
  • 26. 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 ( ) { } 26 By:-GouravKottawar
  • 27. DESTRUCTORS  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. continue … 27 By:-GouravKottawar
  • 28. 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 … 28 By:-GouravKottawar