SlideShare a Scribd company logo
1 of 42
Constructors & Destructors
Constructors
A special member function having same
name as that of its class which is used to
initialize some valid values to the
member variables.
Key points while defining constructor
๏‚žA constructor has same name as that of the class to
which it belongs.
๏‚ž A constructor is executed automatically whenever
the object is created
๏‚žA constructor doesn`t have a return type, not even
void
๏‚ž We can declare more than one constructor in a class.
These constructor differ in there parameter list.
๏‚žIf you donโ€™t provide a constructor of your own then
the compiler generates a default constructor
(expects no parameters and has an empty
body).
๏‚žA constructor can preferably be used for
initialization and not for inputoutput operations.
โ€ข They canโ€™t be inherited; through a derived class,
can call the base class constructor.
โ€ข Like other C++ functions, they can have default
arguments.
โ€ข Constructors canโ€™t be virtual.
โ€ข Constructors can be inside the class definition or
outside the class definition.
โ€ข Constructor canโ€™t be friend function.
โ€ข They canโ€™t be used in union.
Contd..
โ€ข Constructor should be declared in the public section
of the class. If it is not declared in public section of
the class then the whole class become private . By
doing this the object of the class created from
outside cannot invoke the constructor which is the
first member function to be executed
automatically.
Syntax
class CLASSNAME
{
public:
CLASSNAME([parameter list]);
};
Example
#include<iostream.h>
#include<conio.h>
class Rectangle
{
private:
int length,breadth;
public:
Rectangle()
{
length=5,breadth=6;
}
void area()
{
int a=(length*breadth);
cout<<"area is"<<a;
}
};
void main()
{
clrscr();
Rectangle r1;
r1.area();
getch();
}
TYPES OF CONSTRUCTOR
โ€ข 1.Default Constructor
โ€ข 2.Parameterized Constructor
โ€ข 3.Copy Constructor
Parameterized Constructor
In order to initialize various data elements of
different objects with different values when they
are created. C++ permits us to achieve this objects
by passing argument to the constructor function
when the object are created . The constructor that
can take arguments are called parameterized
constructors
class abc
{
int m, n;
public:
abc (int x, int y); // parameterized constructor
................
.................
};
abc : : abc (int x, int y)
{
m = x;
n = y;
}
Parameterized constructor
#include<iostream.h>
#include<conio.h>
class Rectangle
{
private:
int length,breadth;
public:
Rectangle(int a,int b)
{
length=a;
breadth=b;
}
void area()
{
int a=(length*breadth);
cout<<"area is="<<a;
}
};
void main()
{
Rectangle r1(5,6);
Rectangle r2(7,8);
clrscr();
r1.area();cout<<endl;
r2.area();
getch();
}
Copy constructor
โ€ข A constructor is a constructor that creates a new
object using an existing object of the same class
โ€ข and initializes each data member of newly created
object with corresponding data member of existing
object passed as argumnt.
โ€ข since it creates a copy of an existing object so it is
called copy constructor.
Example
class counter
{
Int c;
public:
Counter(int a) //single parameter constructor
{
c=a;
}
counter(counter &ob) //copy constructor
{
cout<<โ€œcopy constructor invokedโ€;
c=ob.c;
}
}
void show()
{
cout<<c;
}
};
void main()
{
clrscr();
counter C1(10);
counter C2(C1);// call copy constructor
C1.show();
C2.show();
getch();
}
Another example of copy constructor
#include<iostream>
#include<conio.h>
using namespace std;
class Point
{
private:
int x, y;
public:
Point(int x1, int y1)
{
x = x1;
y = y1;
}
// Copy constructor
Point(const Point &p2)
{
x = p2.x;
y = p2.y;
}
int getX()
{
return x;
}
int getY()
{
return y;
}
};
int main()
{
Point p1(10, 15); // Normal constructor is called here
Point p2 = p1; // Copy constructor is called here
// Let us access values assigned by constructors
cout << "p1.x = " << p1.getX() << ", p1.y = " << p1.getY();
cout << "np2.x = " << p2.getX() << ", p2.y = " << p2.getY();
return 0;
}
class code
{
int id;
public:
code() { }
code(int a)
{
id = a;
}
code (code & x)
{
id = x. id;
}
void display()
{ cout<<id;
} };
int main()
{
code A(100);
code B(A);
code C = A;
code D;
D = A;
A.display();
B.display();
C.display();
D.display();
getch();
return 0;
}
Destructors
Is a member function having same name
as that of constructor but it is preceded
by a tilde(~) symbol and is executed
automatically when object of a class is
destroyed
Key points while defining destructor
โ€ข A destructor has same name as that of the class to which it belongs
preceded by tilde(~)sign.
โ€ข A destructor is executed automatically whenever the object is destroyed.
โ€ข A destructor doesn`t have a return type, not even void and no arguments
โ€ข There is only one destructor in class .
โ€ข If you donโ€™t provide a destructor of your own then the compiler generates a
default destructor
โ€ข A destructor can be used to deallocate memory for an object and declared
in the public section.
Need for Destructors
โ€ข To de-initialize the objects when they are destroyed
โ€ข To clear memory space occupied by a data
member.
syntax
class CLASSNAME
{
โ€ฆโ€ฆโ€ฆโ€ฆโ€ฆโ€ฆ.
public:
~CLASSNAME([parameter list]);
};
Note
โ€ข Execute the program in Turbo c++.
โ€ข To see the output, press Alt+F5
Program on destructor
Class sample
{
Public:
Sample
{
Cout<<โ€œobject bornโ€<<endl;
}
Public:
{
~sample
{
Cout<<object dies<<endl;
}
};
int main()
{
sample s;
Cout<<โ€œmain terminatedโ€<<endl;
getch();
return 0;
}
Example
#include<iostream.h>
#include<conio.h>
class counter
{
int id;
public:
counter(int i)
{
id=i;
cout<<โ€œcontructor of object with id=โ€<<id;
~counter()
{
cout<<โ€œdestructor with id=โ€<<id;
}
};
void main()
{
counter c1(1);
counter c2(2);
counter c3(3);
cout<<โ€œn end of mainโ€;
getch();
}
โ€ข Output
constructor of object with id=1
constructor of object with id=2
constructor of object with id=3
End of main
destructor with id=3
destructor with id=2
destructor with id=1
Note ::Destructor Always deallocate memory in reverse order.
1 Statically allocated object for class A in C++ is
A *obj = new A();
A obj;
A obj = new A();
None
When you create an object of a class A like A obj ;
then which one will be called automatically
A Constructor
B Destructor
C Copy constructor
D Assignment operator
3 Data members and member functions of a class in
C++ program are by default
protected
public
private
None
4 Which operator is used to allocate an object
dynamically of a class in C++?
Scope resolution operator
Conditional operator
New operator
Membership access
The static member functions __________________
a) Have access to all the members of a class
b) Have access to only constant members of a class
c.) Have access to only the static members of a class
d) Have direct access to all other class members also
The static member functions ____________________
a.) Can be called using class name
b) Can be called using program name
c) Can be called directly
d) Canโ€™t be called outside the function
Which among the following is true?
a) Static member functions can be overloaded
b.) Static member functions canโ€™t be overloaded
c) Static member functions can be overloaded using
derived classes
d) Static member functions are implicitly overloaded
Which keyword should be used to declare the static
member functions?
a.) static
b) stat
c) const
d) common
Assume class TEST. Which of the following statements
is/are responsible to invoke copy constructor?
a. TEST T2(T1)
b. TEST T4 = T1
c. T2 = T1
D). both a and b
Which of the following statements are not true about
destructor?
1. It is invoked when object goes out of the scope
2. Like constructor, it can also have parameters
3. It can be virtual
4. It can be declared in private section
5. It bears same name as that of the class and precedes Lambda
sign.
a. Only 2, 3, 5
b. Only 2, 3, 4
c). Only 2, 4, 5
d. Only 3, 4, 5
A Constructor that does not have any parameters is
called____________ Constructor.
a. Custom
b. Dynamic
c. Static
d). Default
Which of the followings are true about constructors?
1. A class can have more than one constructor.
2. They can be inherited.
3. Their address can be referred.
4. Constructors cannot be declared in protected section of the class.
5. Constructors cannot return values.
a. Only 1,2,4
b. 1,2,4,5
c. 1,3,5
d.) 1,4,5
In a program, If there exists a function template with
two parameters and normal function say void add(int
, int), so add(3,4) will _____________________ .
a. Invoke function template body as it is generic one
b.) Invokes normal function as it exactly matches
with its prototype
c. Not be called and Compiler issues warning
d. Not be called and Compiler issues ambiguity in
calling add()

More Related Content

What's hot

Inheritance
InheritanceInheritance
Inheritanceabhay singh
ย 
Constructor & destructor
Constructor & destructorConstructor & destructor
Constructor & destructorSaharsh Anand
ย 
Functors, Applicatives and Monads In Scala
Functors, Applicatives and Monads In ScalaFunctors, Applicatives and Monads In Scala
Functors, Applicatives and Monads In ScalaKnoldus Inc.
ย 
106da session5 c++
106da session5 c++106da session5 c++
106da session5 c++Mukund Trivedi
ย 
Oop2011 actor presentation_stal
Oop2011 actor presentation_stalOop2011 actor presentation_stal
Oop2011 actor presentation_stalMichael Stal
ย 
Java For Automation
Java   For AutomationJava   For Automation
Java For AutomationAbhijeet Dubey
ย 
2CPP04 - Objects and Classes
2CPP04 - Objects and Classes2CPP04 - Objects and Classes
2CPP04 - Objects and ClassesMichael Heron
ย 
Qcon2011 functions rockpresentation_scala
Qcon2011 functions rockpresentation_scalaQcon2011 functions rockpresentation_scala
Qcon2011 functions rockpresentation_scalaMichael Stal
ย 
Constructors and destructors
Constructors and destructorsConstructors and destructors
Constructors and destructorsVineeta Garg
ย 
16 virtual function
16 virtual function16 virtual function
16 virtual functionDocent Education
ย 
9054799 dzone-refcard267-kotlin
9054799 dzone-refcard267-kotlin9054799 dzone-refcard267-kotlin
9054799 dzone-refcard267-kotlinZoran Stanimirovic
ย 
Of Lambdas and LINQ
Of Lambdas and LINQOf Lambdas and LINQ
Of Lambdas and LINQBlackRabbitCoder
ย 
DIWE - Programming with JavaScript
DIWE - Programming with JavaScriptDIWE - Programming with JavaScript
DIWE - Programming with JavaScriptRasan Samarasinghe
ย 
Oop2010 Scala Presentation Stal
Oop2010 Scala Presentation StalOop2010 Scala Presentation Stal
Oop2010 Scala Presentation StalMichael Stal
ย 
Constructor and destructor in c++
Constructor and destructor in c++Constructor and destructor in c++
Constructor and destructor in c++Learn By Watch
ย 
pointers,virtual functions and polymorphism
pointers,virtual functions and polymorphismpointers,virtual functions and polymorphism
pointers,virtual functions and polymorphismrattaj
ย 
Virtual function complete By Abdul Wahab (moon sheikh)
Virtual function complete By Abdul Wahab (moon sheikh)Virtual function complete By Abdul Wahab (moon sheikh)
Virtual function complete By Abdul Wahab (moon sheikh)MoonSheikh1
ย 

What's hot (20)

Inheritance
InheritanceInheritance
Inheritance
ย 
Constructor & destructor
Constructor & destructorConstructor & destructor
Constructor & destructor
ย 
Functors, Applicatives and Monads In Scala
Functors, Applicatives and Monads In ScalaFunctors, Applicatives and Monads In Scala
Functors, Applicatives and Monads In Scala
ย 
106da session5 c++
106da session5 c++106da session5 c++
106da session5 c++
ย 
Oop2011 actor presentation_stal
Oop2011 actor presentation_stalOop2011 actor presentation_stal
Oop2011 actor presentation_stal
ย 
Java For Automation
Java   For AutomationJava   For Automation
Java For Automation
ย 
2CPP04 - Objects and Classes
2CPP04 - Objects and Classes2CPP04 - Objects and Classes
2CPP04 - Objects and Classes
ย 
Qcon2011 functions rockpresentation_scala
Qcon2011 functions rockpresentation_scalaQcon2011 functions rockpresentation_scala
Qcon2011 functions rockpresentation_scala
ย 
Constructors and destructors
Constructors and destructorsConstructors and destructors
Constructors and destructors
ย 
16 virtual function
16 virtual function16 virtual function
16 virtual function
ย 
9054799 dzone-refcard267-kotlin
9054799 dzone-refcard267-kotlin9054799 dzone-refcard267-kotlin
9054799 dzone-refcard267-kotlin
ย 
Of Lambdas and LINQ
Of Lambdas and LINQOf Lambdas and LINQ
Of Lambdas and LINQ
ย 
DIWE - Programming with JavaScript
DIWE - Programming with JavaScriptDIWE - Programming with JavaScript
DIWE - Programming with JavaScript
ย 
Object-Oriented Programming Using C++
Object-Oriented Programming Using C++Object-Oriented Programming Using C++
Object-Oriented Programming Using C++
ย 
Constructors and Destructors
Constructors and DestructorsConstructors and Destructors
Constructors and Destructors
ย 
Oop2010 Scala Presentation Stal
Oop2010 Scala Presentation StalOop2010 Scala Presentation Stal
Oop2010 Scala Presentation Stal
ย 
Constructor and destructor in c++
Constructor and destructor in c++Constructor and destructor in c++
Constructor and destructor in c++
ย 
pointers,virtual functions and polymorphism
pointers,virtual functions and polymorphismpointers,virtual functions and polymorphism
pointers,virtual functions and polymorphism
ย 
C++
C++C++
C++
ย 
Virtual function complete By Abdul Wahab (moon sheikh)
Virtual function complete By Abdul Wahab (moon sheikh)Virtual function complete By Abdul Wahab (moon sheikh)
Virtual function complete By Abdul Wahab (moon sheikh)
ย 

Similar to Constructors and destructors in C++ part 2

Constructors in C++.pptx
Constructors in C++.pptxConstructors in C++.pptx
Constructors in C++.pptxRassjb
ย 
CONSTRUCTORS IN C++ +2 COMPUTER SCIENCE
CONSTRUCTORS IN C++ +2 COMPUTER SCIENCECONSTRUCTORS IN C++ +2 COMPUTER SCIENCE
CONSTRUCTORS IN C++ +2 COMPUTER SCIENCEVenugopalavarma Raja
ย 
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 in c++
Constructor  and Destructor in c++Constructor  and Destructor in c++
Constructor and Destructor in c++aleenaguen
ย 
Constructor and destructor
Constructor and destructorConstructor and destructor
Constructor and destructorrajshreemuthiah
ย 
Constructor and Destructor
Constructor and DestructorConstructor and Destructor
Constructor and DestructorSunipa Bera
ย 
Learning C++ - Class 4
Learning C++ - Class 4Learning C++ - Class 4
Learning C++ - Class 4Ali Aminian
ย 
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
ย 
Constructors and destructors
Constructors and destructorsConstructors and destructors
Constructors and destructorsProf. Dr. K. Adisesha
ย 
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
ย 
Bca 2nd sem u-2 classes & objects
Bca 2nd sem u-2 classes & objectsBca 2nd sem u-2 classes & objects
Bca 2nd sem u-2 classes & objectsRai University
ย 
Constructor
ConstructorConstructor
Constructorabhay singh
ย 
Mca 2nd sem u-2 classes & objects
Mca 2nd  sem u-2 classes & objectsMca 2nd  sem u-2 classes & objects
Mca 2nd sem u-2 classes & objectsRai University
ย 
[OOP - Lec 13,14,15] Constructors / Destructor and its Types
[OOP - Lec 13,14,15] Constructors / Destructor and its Types[OOP - Lec 13,14,15] Constructors / Destructor and its Types
[OOP - Lec 13,14,15] Constructors / Destructor and its TypesMuhammad Hammad Waseem
ย 
Constructor and desturctor
Constructor and desturctorConstructor and desturctor
Constructor and desturctorSomnath Kulkarni
ย 

Similar to Constructors and destructors in C++ part 2 (20)

Constructors in C++.pptx
Constructors in C++.pptxConstructors in C++.pptx
Constructors in C++.pptx
ย 
Constructors and Destructor in C++
Constructors and Destructor in C++Constructors and Destructor in C++
Constructors and Destructor in C++
ย 
CONSTRUCTORS IN C++ +2 COMPUTER SCIENCE
CONSTRUCTORS IN C++ +2 COMPUTER SCIENCECONSTRUCTORS IN C++ +2 COMPUTER SCIENCE
CONSTRUCTORS IN C++ +2 COMPUTER SCIENCE
ย 
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 in c++
Constructor  and Destructor in c++Constructor  and Destructor in c++
Constructor and Destructor in c++
ย 
Constructor and destructor
Constructor and destructorConstructor and destructor
Constructor and destructor
ย 
Constructor and Destructor
Constructor and DestructorConstructor and Destructor
Constructor and Destructor
ย 
Learning C++ - Class 4
Learning C++ - Class 4Learning C++ - Class 4
Learning C++ - Class 4
ย 
Oops
OopsOops
Oops
ย 
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++
ย 
Constructors and destructors
Constructors and destructorsConstructors and destructors
Constructors and destructors
ย 
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
ย 
Bca 2nd sem u-2 classes & objects
Bca 2nd sem u-2 classes & objectsBca 2nd sem u-2 classes & objects
Bca 2nd sem u-2 classes & objects
ย 
Constructor
ConstructorConstructor
Constructor
ย 
Mca 2nd sem u-2 classes & objects
Mca 2nd  sem u-2 classes & objectsMca 2nd  sem u-2 classes & objects
Mca 2nd sem u-2 classes & objects
ย 
Constructor,destructors cpp
Constructor,destructors cppConstructor,destructors cpp
Constructor,destructors cpp
ย 
[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
ย 
C++.pptx
C++.pptxC++.pptx
C++.pptx
ย 
Constructor and desturctor
Constructor and desturctorConstructor and desturctor
Constructor and desturctor
ย 

More from Lovely Professional University (20)

Constructor and destructor in C++
Constructor and destructor in C++Constructor and destructor in C++
Constructor and destructor in C++
ย 
Classes and objects
Classes and objectsClasses and objects
Classes and objects
ย 
Cin and cout
Cin and coutCin and cout
Cin and cout
ย 
Major project synopsis format
Major project synopsis formatMajor project synopsis format
Major project synopsis format
ย 
Docslide.net soyabean milk-project-class-12
Docslide.net soyabean milk-project-class-12Docslide.net soyabean milk-project-class-12
Docslide.net soyabean milk-project-class-12
ย 
Physics first page
Physics first pagePhysics first page
Physics first page
ย 
Uses of transformer
Uses of transformerUses of transformer
Uses of transformer
ย 
Theory and working
Theory and workingTheory and working
Theory and working
ย 
Main page vishnu
Main page vishnuMain page vishnu
Main page vishnu
ย 
Main page v physics
Main page v physicsMain page v physics
Main page v physics
ย 
Main page saurabh
Main page  saurabhMain page  saurabh
Main page saurabh
ย 
Introduction
IntroductionIntroduction
Introduction
ย 
Efficiency and energy losses
Efficiency and energy lossesEfficiency and energy losses
Efficiency and energy losses
ย 
Contents
ContentsContents
Contents
ย 
Certificate
CertificateCertificate
Certificate
ย 
Bibliography
BibliographyBibliography
Bibliography
ย 
Apparatus
ApparatusApparatus
Apparatus
ย 
Acknowledgement
AcknowledgementAcknowledgement
Acknowledgement
ย 
Principle construction
Principle constructionPrinciple construction
Principle construction
ย 
Theory and procedure
Theory and procedureTheory and procedure
Theory and procedure
ย 

Recently uploaded

Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...roncy bisnoi
ย 
Thermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.pptThermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.pptDineshKumar4165
ย 
2016EF22_0 solar project report rooftop projects
2016EF22_0 solar project report rooftop projects2016EF22_0 solar project report rooftop projects
2016EF22_0 solar project report rooftop projectssmsksolar
ย 
Minimum and Maximum Modes of microprocessor 8086
Minimum and Maximum Modes of microprocessor 8086Minimum and Maximum Modes of microprocessor 8086
Minimum and Maximum Modes of microprocessor 8086anil_gaur
ย 
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756dollysharma2066
ย 
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance BookingCall Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance Bookingroncy bisnoi
ย 
Standard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power PlayStandard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power PlayEpec Engineered Technologies
ย 
Generative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPTGenerative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPTbhaskargani46
ย 
data_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdfdata_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdfJiananWang21
ย 
University management System project report..pdf
University management System project report..pdfUniversity management System project report..pdf
University management System project report..pdfKamal Acharya
ย 
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdfONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdfKamal Acharya
ย 
Design For Accessibility: Getting it right from the start
Design For Accessibility: Getting it right from the startDesign For Accessibility: Getting it right from the start
Design For Accessibility: Getting it right from the startQuintin Balsdon
ย 
Hazard Identification (HAZID) vs. Hazard and Operability (HAZOP): A Comparati...
Hazard Identification (HAZID) vs. Hazard and Operability (HAZOP): A Comparati...Hazard Identification (HAZID) vs. Hazard and Operability (HAZOP): A Comparati...
Hazard Identification (HAZID) vs. Hazard and Operability (HAZOP): A Comparati...soginsider
ย 
Thermal Engineering Unit - I & II . ppt
Thermal Engineering  Unit - I & II . pptThermal Engineering  Unit - I & II . ppt
Thermal Engineering Unit - I & II . pptDineshKumar4165
ย 
Hostel management system project report..pdf
Hostel management system project report..pdfHostel management system project report..pdf
Hostel management system project report..pdfKamal Acharya
ย 
Bhosari ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready For ...
Bhosari ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready For ...Bhosari ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready For ...
Bhosari ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready For ...tanu pandey
ย 
Top Rated Call Girls In chittoor ๐Ÿ“ฑ {7001035870} VIP Escorts chittoor
Top Rated Call Girls In chittoor ๐Ÿ“ฑ {7001035870} VIP Escorts chittoorTop Rated Call Girls In chittoor ๐Ÿ“ฑ {7001035870} VIP Escorts chittoor
Top Rated Call Girls In chittoor ๐Ÿ“ฑ {7001035870} VIP Escorts chittoordharasingh5698
ย 
COST-EFFETIVE and Energy Efficient BUILDINGS ptx
COST-EFFETIVE  and Energy Efficient BUILDINGS ptxCOST-EFFETIVE  and Energy Efficient BUILDINGS ptx
COST-EFFETIVE and Energy Efficient BUILDINGS ptxJIT KUMAR GUPTA
ย 
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Bookingdharasingh5698
ย 
Call Now โ‰ฝ 9953056974 โ‰ผ๐Ÿ” Call Girls In New Ashok Nagar โ‰ผ๐Ÿ” Delhi door step de...
Call Now โ‰ฝ 9953056974 โ‰ผ๐Ÿ” Call Girls In New Ashok Nagar  โ‰ผ๐Ÿ” Delhi door step de...Call Now โ‰ฝ 9953056974 โ‰ผ๐Ÿ” Call Girls In New Ashok Nagar  โ‰ผ๐Ÿ” Delhi door step de...
Call Now โ‰ฝ 9953056974 โ‰ผ๐Ÿ” Call Girls In New Ashok Nagar โ‰ผ๐Ÿ” Delhi door step de...9953056974 Low Rate Call Girls In Saket, Delhi NCR
ย 

Recently uploaded (20)

Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
ย 
Thermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.pptThermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.ppt
ย 
2016EF22_0 solar project report rooftop projects
2016EF22_0 solar project report rooftop projects2016EF22_0 solar project report rooftop projects
2016EF22_0 solar project report rooftop projects
ย 
Minimum and Maximum Modes of microprocessor 8086
Minimum and Maximum Modes of microprocessor 8086Minimum and Maximum Modes of microprocessor 8086
Minimum and Maximum Modes of microprocessor 8086
ย 
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
ย 
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance BookingCall Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
ย 
Standard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power PlayStandard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power Play
ย 
Generative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPTGenerative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPT
ย 
data_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdfdata_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdf
ย 
University management System project report..pdf
University management System project report..pdfUniversity management System project report..pdf
University management System project report..pdf
ย 
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdfONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ย 
Design For Accessibility: Getting it right from the start
Design For Accessibility: Getting it right from the startDesign For Accessibility: Getting it right from the start
Design For Accessibility: Getting it right from the start
ย 
Hazard Identification (HAZID) vs. Hazard and Operability (HAZOP): A Comparati...
Hazard Identification (HAZID) vs. Hazard and Operability (HAZOP): A Comparati...Hazard Identification (HAZID) vs. Hazard and Operability (HAZOP): A Comparati...
Hazard Identification (HAZID) vs. Hazard and Operability (HAZOP): A Comparati...
ย 
Thermal Engineering Unit - I & II . ppt
Thermal Engineering  Unit - I & II . pptThermal Engineering  Unit - I & II . ppt
Thermal Engineering Unit - I & II . ppt
ย 
Hostel management system project report..pdf
Hostel management system project report..pdfHostel management system project report..pdf
Hostel management system project report..pdf
ย 
Bhosari ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready For ...
Bhosari ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready For ...Bhosari ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready For ...
Bhosari ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready For ...
ย 
Top Rated Call Girls In chittoor ๐Ÿ“ฑ {7001035870} VIP Escorts chittoor
Top Rated Call Girls In chittoor ๐Ÿ“ฑ {7001035870} VIP Escorts chittoorTop Rated Call Girls In chittoor ๐Ÿ“ฑ {7001035870} VIP Escorts chittoor
Top Rated Call Girls In chittoor ๐Ÿ“ฑ {7001035870} VIP Escorts chittoor
ย 
COST-EFFETIVE and Energy Efficient BUILDINGS ptx
COST-EFFETIVE  and Energy Efficient BUILDINGS ptxCOST-EFFETIVE  and Energy Efficient BUILDINGS ptx
COST-EFFETIVE and Energy Efficient BUILDINGS ptx
ย 
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
ย 
Call Now โ‰ฝ 9953056974 โ‰ผ๐Ÿ” Call Girls In New Ashok Nagar โ‰ผ๐Ÿ” Delhi door step de...
Call Now โ‰ฝ 9953056974 โ‰ผ๐Ÿ” Call Girls In New Ashok Nagar  โ‰ผ๐Ÿ” Delhi door step de...Call Now โ‰ฝ 9953056974 โ‰ผ๐Ÿ” Call Girls In New Ashok Nagar  โ‰ผ๐Ÿ” Delhi door step de...
Call Now โ‰ฝ 9953056974 โ‰ผ๐Ÿ” Call Girls In New Ashok Nagar โ‰ผ๐Ÿ” Delhi door step de...
ย 

Constructors and destructors in C++ part 2

  • 2. Constructors A special member function having same name as that of its class which is used to initialize some valid values to the member variables.
  • 3. Key points while defining constructor ๏‚žA constructor has same name as that of the class to which it belongs. ๏‚ž A constructor is executed automatically whenever the object is created ๏‚žA constructor doesn`t have a return type, not even void ๏‚ž We can declare more than one constructor in a class. These constructor differ in there parameter list. ๏‚žIf you donโ€™t provide a constructor of your own then the compiler generates a default constructor (expects no parameters and has an empty body). ๏‚žA constructor can preferably be used for initialization and not for inputoutput operations.
  • 4. โ€ข They canโ€™t be inherited; through a derived class, can call the base class constructor. โ€ข Like other C++ functions, they can have default arguments. โ€ข Constructors canโ€™t be virtual. โ€ข Constructors can be inside the class definition or outside the class definition. โ€ข Constructor canโ€™t be friend function. โ€ข They canโ€™t be used in union.
  • 5. Contd.. โ€ข Constructor should be declared in the public section of the class. If it is not declared in public section of the class then the whole class become private . By doing this the object of the class created from outside cannot invoke the constructor which is the first member function to be executed automatically.
  • 7. Example #include<iostream.h> #include<conio.h> class Rectangle { private: int length,breadth; public: Rectangle() { length=5,breadth=6; } void area() { int a=(length*breadth); cout<<"area is"<<a; } }; void main() { clrscr(); Rectangle r1; r1.area(); getch(); }
  • 8. TYPES OF CONSTRUCTOR โ€ข 1.Default Constructor โ€ข 2.Parameterized Constructor โ€ข 3.Copy Constructor
  • 9. Parameterized Constructor In order to initialize various data elements of different objects with different values when they are created. C++ permits us to achieve this objects by passing argument to the constructor function when the object are created . The constructor that can take arguments are called parameterized constructors
  • 10. class abc { int m, n; public: abc (int x, int y); // parameterized constructor ................ ................. }; abc : : abc (int x, int y) { m = x; n = y; }
  • 11. Parameterized constructor #include<iostream.h> #include<conio.h> class Rectangle { private: int length,breadth; public: Rectangle(int a,int b) { length=a; breadth=b; } void area() { int a=(length*breadth); cout<<"area is="<<a; } }; void main() { Rectangle r1(5,6); Rectangle r2(7,8); clrscr(); r1.area();cout<<endl; r2.area(); getch(); }
  • 12. Copy constructor โ€ข A constructor is a constructor that creates a new object using an existing object of the same class โ€ข and initializes each data member of newly created object with corresponding data member of existing object passed as argumnt. โ€ข since it creates a copy of an existing object so it is called copy constructor.
  • 13. Example class counter { Int c; public: Counter(int a) //single parameter constructor { c=a; } counter(counter &ob) //copy constructor { cout<<โ€œcopy constructor invokedโ€; c=ob.c; } }
  • 14. void show() { cout<<c; } }; void main() { clrscr(); counter C1(10); counter C2(C1);// call copy constructor C1.show(); C2.show(); getch(); }
  • 15. Another example of copy constructor #include<iostream> #include<conio.h> using namespace std; class Point { private: int x, y; public: Point(int x1, int y1) { x = x1; y = y1; }
  • 16. // Copy constructor Point(const Point &p2) { x = p2.x; y = p2.y; } int getX() { return x; } int getY() { return y; } };
  • 17. int main() { Point p1(10, 15); // Normal constructor is called here Point p2 = p1; // Copy constructor is called here // Let us access values assigned by constructors cout << "p1.x = " << p1.getX() << ", p1.y = " << p1.getY(); cout << "np2.x = " << p2.getX() << ", p2.y = " << p2.getY(); return 0; }
  • 18. class code { int id; public: code() { } code(int a) { id = a; } code (code & x) { id = x. id; } void display() { cout<<id; } }; int main() { code A(100); code B(A); code C = A; code D; D = A; A.display(); B.display(); C.display(); D.display(); getch(); return 0; }
  • 19. Destructors Is a member function having same name as that of constructor but it is preceded by a tilde(~) symbol and is executed automatically when object of a class is destroyed
  • 20. Key points while defining destructor โ€ข A destructor has same name as that of the class to which it belongs preceded by tilde(~)sign. โ€ข A destructor is executed automatically whenever the object is destroyed. โ€ข A destructor doesn`t have a return type, not even void and no arguments โ€ข There is only one destructor in class . โ€ข If you donโ€™t provide a destructor of your own then the compiler generates a default destructor โ€ข A destructor can be used to deallocate memory for an object and declared in the public section.
  • 21. Need for Destructors โ€ข To de-initialize the objects when they are destroyed โ€ข To clear memory space occupied by a data member.
  • 23. Note โ€ข Execute the program in Turbo c++. โ€ข To see the output, press Alt+F5
  • 24. Program on destructor Class sample { Public: Sample { Cout<<โ€œobject bornโ€<<endl; }
  • 26. int main() { sample s; Cout<<โ€œmain terminatedโ€<<endl; getch(); return 0; }
  • 27. Example #include<iostream.h> #include<conio.h> class counter { int id; public: counter(int i) { id=i; cout<<โ€œcontructor of object with id=โ€<<id;
  • 28. ~counter() { cout<<โ€œdestructor with id=โ€<<id; } }; void main() { counter c1(1); counter c2(2); counter c3(3); cout<<โ€œn end of mainโ€; getch(); }
  • 29. โ€ข Output constructor of object with id=1 constructor of object with id=2 constructor of object with id=3 End of main destructor with id=3 destructor with id=2 destructor with id=1 Note ::Destructor Always deallocate memory in reverse order.
  • 30. 1 Statically allocated object for class A in C++ is A *obj = new A(); A obj; A obj = new A(); None
  • 31. When you create an object of a class A like A obj ; then which one will be called automatically A Constructor B Destructor C Copy constructor D Assignment operator
  • 32. 3 Data members and member functions of a class in C++ program are by default protected public private None
  • 33. 4 Which operator is used to allocate an object dynamically of a class in C++? Scope resolution operator Conditional operator New operator Membership access
  • 34. The static member functions __________________ a) Have access to all the members of a class b) Have access to only constant members of a class c.) Have access to only the static members of a class d) Have direct access to all other class members also
  • 35. The static member functions ____________________ a.) Can be called using class name b) Can be called using program name c) Can be called directly d) Canโ€™t be called outside the function
  • 36. Which among the following is true? a) Static member functions can be overloaded b.) Static member functions canโ€™t be overloaded c) Static member functions can be overloaded using derived classes d) Static member functions are implicitly overloaded
  • 37. Which keyword should be used to declare the static member functions? a.) static b) stat c) const d) common
  • 38. Assume class TEST. Which of the following statements is/are responsible to invoke copy constructor? a. TEST T2(T1) b. TEST T4 = T1 c. T2 = T1 D). both a and b
  • 39. Which of the following statements are not true about destructor? 1. It is invoked when object goes out of the scope 2. Like constructor, it can also have parameters 3. It can be virtual 4. It can be declared in private section 5. It bears same name as that of the class and precedes Lambda sign. a. Only 2, 3, 5 b. Only 2, 3, 4 c). Only 2, 4, 5 d. Only 3, 4, 5
  • 40. A Constructor that does not have any parameters is called____________ Constructor. a. Custom b. Dynamic c. Static d). Default
  • 41. Which of the followings are true about constructors? 1. A class can have more than one constructor. 2. They can be inherited. 3. Their address can be referred. 4. Constructors cannot be declared in protected section of the class. 5. Constructors cannot return values. a. Only 1,2,4 b. 1,2,4,5 c. 1,3,5 d.) 1,4,5
  • 42. In a program, If there exists a function template with two parameters and normal function say void add(int , int), so add(3,4) will _____________________ . a. Invoke function template body as it is generic one b.) Invokes normal function as it exactly matches with its prototype c. Not be called and Compiler issues warning d. Not be called and Compiler issues ambiguity in calling add()