SlideShare a Scribd company logo
1 of 28
Learners Support Publications www.lsp4you.com
Constructors and
Destructors
Learners Support Publications www.lsp4you.com
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.
Learners Support Publications www.lsp4you.com
Constructor - example
class add
{
int m, n ;
public :
add () ;
------
};
add :: add ()
{
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.
Learners Support Publications www.lsp4you.com
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 …
Learners Support Publications www.lsp4you.com
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.
Learners Support Publications www.lsp4you.com
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 …
Learners Support Publications www.lsp4you.com
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 …
Learners Support Publications www.lsp4you.com
Constructors
• When a constructor is declared for a class
initialization of the class objects becomes
mandatory.
continue …
Learners Support Publications www.lsp4you.com
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.
Learners Support Publications www.lsp4you.com
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 …
Learners Support Publications www.lsp4you.com
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
Learners Support Publications www.lsp4you.com
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 …
Learners Support Publications www.lsp4you.com
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 …
Learners Support Publications www.lsp4you.com
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 …
Learners Support Publications www.lsp4you.com
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 …
Learners Support Publications www.lsp4you.com
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 …
Learners Support Publications www.lsp4you.com
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.
Learners Support Publications www.lsp4you.com
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 …
Learners Support Publications www.lsp4you.com
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.
Learners Support Publications www.lsp4you.com
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.
Learners Support Publications www.lsp4you.com
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 …
Learners Support Publications www.lsp4you.com
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 …
Learners Support Publications www.lsp4you.com
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.
Learners Support Publications www.lsp4you.com
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 …
Learners Support Publications www.lsp4you.com
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 ( ) { }
Learners Support Publications www.lsp4you.com
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 …
Learners Support Publications www.lsp4you.com
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 …
Learners Support Publications www.lsp4you.com
Thank You

More Related Content

Similar to constructor.ppt

Constructors and destructors
Constructors and destructorsConstructors and destructors
Constructors and destructorsNilesh Dalvi
 
Constructor and Destructor
Constructor and DestructorConstructor and Destructor
Constructor and DestructorSunipa Bera
 
C++ Constructor and Destructors.pptx
C++ Constructor and Destructors.pptxC++ Constructor and Destructors.pptx
C++ Constructor and Destructors.pptxsasukeman
 
B.sc CSIT 2nd semester C++ Unit3
B.sc CSIT  2nd semester C++ Unit3B.sc CSIT  2nd semester C++ Unit3
B.sc CSIT 2nd semester C++ Unit3Tekendra Nath Yogi
 
Constructor& destructor
Constructor& destructorConstructor& destructor
Constructor& destructorchauhankapil
 
constructor & destructor in cpp
constructor & destructor in cppconstructor & destructor in cpp
constructor & destructor in cppgourav kottawar
 
constructor & destructor in cpp
constructor & destructor in cppconstructor & destructor in cpp
constructor & destructor in cppgourav kottawar
 
Oop lec 5-(class objects, constructor & destructor)
Oop lec 5-(class objects, constructor & destructor)Oop lec 5-(class objects, constructor & destructor)
Oop lec 5-(class objects, constructor & destructor)Asfand Hassan
 
CONSTRUCTORS IN C++ +2 COMPUTER SCIENCE
CONSTRUCTORS IN C++ +2 COMPUTER SCIENCECONSTRUCTORS IN C++ +2 COMPUTER SCIENCE
CONSTRUCTORS IN C++ +2 COMPUTER SCIENCEVenugopalavarma Raja
 
object oriented programming language.pptx
object oriented programming language.pptxobject oriented programming language.pptx
object oriented programming language.pptxsyedabbas594247
 
Introductions to Constructors.pptx
Introductions to Constructors.pptxIntroductions to Constructors.pptx
Introductions to Constructors.pptxSouravKrishnaBaul
 
constructorsfjy5ediykEASFul;IUWORHusi;gfb.pptx
constructorsfjy5ediykEASFul;IUWORHusi;gfb.pptxconstructorsfjy5ediykEASFul;IUWORHusi;gfb.pptx
constructorsfjy5ediykEASFul;IUWORHusi;gfb.pptxAshrithaRokkam
 
constructor in object oriented program.pptx
constructor in object oriented program.pptxconstructor in object oriented program.pptx
constructor in object oriented program.pptxurvashipundir04
 
Constructor and Destructor.pdf
Constructor and Destructor.pdfConstructor and Destructor.pdf
Constructor and Destructor.pdfMadnessKnight
 
Constructor & destructor
Constructor & destructorConstructor & destructor
Constructor & destructorSaharsh Anand
 

Similar to constructor.ppt (20)

Constructors and destructors
Constructors and destructorsConstructors and destructors
Constructors and destructors
 
Constructors and Destructor in C++
Constructors and Destructor in C++Constructors and Destructor in C++
Constructors and Destructor in C++
 
Constructor and Destructor
Constructor and DestructorConstructor and Destructor
Constructor and Destructor
 
C++ Constructor and Destructors.pptx
C++ Constructor and Destructors.pptxC++ Constructor and Destructors.pptx
C++ Constructor and Destructors.pptx
 
B.sc CSIT 2nd semester C++ Unit3
B.sc CSIT  2nd semester C++ Unit3B.sc CSIT  2nd semester C++ Unit3
B.sc CSIT 2nd semester C++ Unit3
 
106da session5 c++
106da session5 c++106da session5 c++
106da session5 c++
 
Constructor& destructor
Constructor& destructorConstructor& destructor
Constructor& destructor
 
constructor & destructor in cpp
constructor & destructor in cppconstructor & destructor in cpp
constructor & destructor in cpp
 
constructor & destructor in cpp
constructor & destructor in cppconstructor & destructor in cpp
constructor & destructor in cpp
 
Oop lec 5-(class objects, constructor & destructor)
Oop lec 5-(class objects, constructor & destructor)Oop lec 5-(class objects, constructor & destructor)
Oop lec 5-(class objects, constructor & destructor)
 
Constructors and Destructors
Constructors and DestructorsConstructors and Destructors
Constructors and Destructors
 
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
 
object oriented programming language.pptx
object oriented programming language.pptxobject oriented programming language.pptx
object oriented programming language.pptx
 
Introductions to Constructors.pptx
Introductions to Constructors.pptxIntroductions to Constructors.pptx
Introductions to Constructors.pptx
 
constructorsfjy5ediykEASFul;IUWORHusi;gfb.pptx
constructorsfjy5ediykEASFul;IUWORHusi;gfb.pptxconstructorsfjy5ediykEASFul;IUWORHusi;gfb.pptx
constructorsfjy5ediykEASFul;IUWORHusi;gfb.pptx
 
constructor in object oriented program.pptx
constructor in object oriented program.pptxconstructor in object oriented program.pptx
constructor in object oriented program.pptx
 
Constructor and Destructor.pdf
Constructor and Destructor.pdfConstructor and Destructor.pdf
Constructor and Destructor.pdf
 
Constructors and destructors
Constructors and destructorsConstructors and destructors
Constructors and destructors
 
Constructor & destructor
Constructor & destructorConstructor & destructor
Constructor & destructor
 

More from nivedita murugan

performance evaluation of parallel processors.pptx
performance evaluation of parallel processors.pptxperformance evaluation of parallel processors.pptx
performance evaluation of parallel processors.pptxnivedita murugan
 
Performance of processor.ppt
Performance of processor.pptPerformance of processor.ppt
Performance of processor.pptnivedita murugan
 

More from nivedita murugan (7)

HTML_Forms_.ppt
HTML_Forms_.pptHTML_Forms_.ppt
HTML_Forms_.ppt
 
Types of Memory.ppt
Types of Memory.pptTypes of Memory.ppt
Types of Memory.ppt
 
Number_Systems (2).ppt
Number_Systems (2).pptNumber_Systems (2).ppt
Number_Systems (2).ppt
 
performance evaluation of parallel processors.pptx
performance evaluation of parallel processors.pptxperformance evaluation of parallel processors.pptx
performance evaluation of parallel processors.pptx
 
Function Overloading.ppt
Function Overloading.pptFunction Overloading.ppt
Function Overloading.ppt
 
Performance of processor.ppt
Performance of processor.pptPerformance of processor.ppt
Performance of processor.ppt
 
Data Representation.pptx
Data Representation.pptxData Representation.pptx
Data Representation.pptx
 

Recently uploaded

How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17Celine George
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docxPoojaSen20
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfUmakantAnnand
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
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
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesFatimaKhan178732
 

Recently uploaded (20)

Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docx
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.Compdf
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
9953330565 Low Rate Call Girls In Rohini Delhi NCR
9953330565 Low Rate Call Girls In Rohini  Delhi NCR9953330565 Low Rate Call Girls In Rohini  Delhi NCR
9953330565 Low Rate Call Girls In Rohini Delhi NCR
 
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 🔝✔️✔️
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and Actinides
 

constructor.ppt

  • 1. Learners Support Publications www.lsp4you.com Constructors and Destructors
  • 2. Learners Support Publications www.lsp4you.com 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. Learners Support Publications www.lsp4you.com Constructor - example class add { int m, n ; public : add () ; ------ }; add :: add () { 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. Learners Support Publications www.lsp4you.com 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. Learners Support Publications www.lsp4you.com 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. Learners Support Publications www.lsp4you.com 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. Learners Support Publications www.lsp4you.com 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. Learners Support Publications www.lsp4you.com Constructors • When a constructor is declared for a class initialization of the class objects becomes mandatory. continue …
  • 9. Learners Support Publications www.lsp4you.com 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. Learners Support Publications www.lsp4you.com 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. Learners Support Publications www.lsp4you.com 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. Learners Support Publications www.lsp4you.com 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. Learners Support Publications www.lsp4you.com 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. Learners Support Publications www.lsp4you.com 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. Learners Support Publications www.lsp4you.com 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. Learners Support Publications www.lsp4you.com 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. Learners Support Publications www.lsp4you.com 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. Learners Support Publications www.lsp4you.com 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. Learners Support Publications www.lsp4you.com 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. Learners Support Publications www.lsp4you.com 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. Learners Support Publications www.lsp4you.com 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. Learners Support Publications www.lsp4you.com 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. Learners Support Publications www.lsp4you.com 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. Learners Support Publications www.lsp4you.com 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. Learners Support Publications www.lsp4you.com 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. Learners Support Publications www.lsp4you.com 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. Learners Support Publications www.lsp4you.com 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. Learners Support Publications www.lsp4you.com Thank You