SlideShare a Scribd company logo
1 of 37
ObjectivesIn this chapter you will learn:
About default constructors
How to create parameterized constructors
How to work with initialization lists
How to create copy constructors
1
Advanced Constructors
Constructors can do more than initialize data
members
They can execute member functions and
perform other types of initialization routines
that a class may require when it first starts
2
Default Constructors
The default constructor does not include
parameters, and is called for any declared objects
of its class to which you do not pass arguments
Remember that you define and declare
constructor functions the same way you define
other functions, although you do not include a
return type because constructor functions do not
return values
3
Constructor Function
4
A Constructor is a special member function
whose task is to initialize the object of its
class. It is special because it name is same as
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.
Default Constructors
The constructor function in Figure is an example
of a default constructor
In addition to initializing data members and
executing member functions, default constructors
perform various types of behind-the-scenes class
maintenance
5
Simple Program
6
// default constructor
#include<iostream>
Using namespace std;
Class integer
{
Int m,n;
Public:
Integer(void); // constructor declared
Void getinfo( );
};
Integer :: integer void( ) // constructor defined
{
m= 0;
n=0;
}
Parameterized Constructors
The constructor integer( ) define above initialize the
data members of all the objects to zero. However is
practice it may be necessary to initialize the various
data elements of different objects with different values,
when they are created.
A parameterized constructor allows a client to pass
initialization values to your class during object
instantiation
Instead of assigning default values, you can allow a
client to pass in the value for these data members by
designing the constructor function with parameters.
7
8
Class integer
{
Int m, n;
Public :
Integer (int x, int y);
};
Integer :: integer(int x,int y)
{
m= x;
n=y;
}
By Calling the Constructor explicitly
By Calling the consructor implicitly
 integer int1 = integer(0,100);
Explicitly called
Integer int1(0,100)
Implicitly called.
Shorthand method.
9
Copy Constructor
There will be times when you want to instantiate a
new object based on an existing object
C++ uses a copy constructor to exactly copy each of
the first object’s data members into the second
object’s data members in an operation known as
member wise copying
A copy constructor is a special constructor that is
called when a new object is instantiated from an old
object
10
Copy Constructor
The syntax for a copy constructor declaration is
class_name :: class_name (class_name &ptr)
The Copy Constructor may be used in the following format
also using a const keyword.
class_name :: class_name (const class_name & ptr)
Copy Constructor are always used when the compiler has to
create a temporary object of a class object.The copy
constructor are used in the following situations:-
The Initialization of an object by another object of the same
class.
Return of object as a function value.
Stating the object as by value parameters of a function.
11
Copy Constructor Example with Program
//fibonacci series using copy constructor
#include<iostream>
Using namespaces std ;
Class fibonacci {
Private :
Unsigned long int f0,f1,fib;
Public :
Fiboancci () // constructor
{
F0=0;
F1=1;
Fib=f0+f1;
}
Fibonacci (fibonacci &ptr) // copy construtor
{
F0=ptr.f0;
F1=ptr.f1;
Fib=prt.fib;
}
12
Void increment ( )
{
F0=f1;
F1=fib;
Fib=f0+f1;
}
Void display ( )
{
Cout<<fib<<‘/t’;
}
};
Void main( )
{
Fibonacci number ;
For(int i=0;i<=15;++i)
{
Number.display();
Number.increment();
}
}
#include<iostream> void display (void)
Using namespace std ; { cout<<id;
Class code // class name }
{ };
Int id; int main()
Public : {
Code() code A(100);//object A is created
// constructor name same as class name code B(A); // copy const. called
{ code C= A; // CC called again
} code D; // D is created, not intilized
Code(int a ) { // constructor again D=A; // C C not called
Id=a; cout<<“n” id of A:=A.display();
} cout<<“n” id of B:=B.display();
Code (code &x) // copy constuctor cout<<“n” id of C:=C.display();
{ id=x.id; // copy in the value cout<<“n” id of D:=D.display();
} return 0;
}
13
Destructors
Just as a default constructor is called when a class
object is first instantiated, a default destructor is
called when the object is destroyed
A default destructor cleans up any resources
allocated to an object once the object is destroyed
The default destructor is sufficient for most
classes, except when you have allocated memory
on the heap
14
Destructors
You create a destructor function using the name of
the class, the same as a constructor
A destructor is commonly called in two ways:
When a stack object loses scope because the function in
which it is declared ends
When a heap object is destroyed with the delete operator
15
Syntax rules for writing a dectructor function :
A destructor function name is the same as that of the
class it belongs except that the first character of the
name must be a tilde ( ~).
It is declared with no return types ( not even void)
since it cannot even return a value.
It cannot de declared static ,const or volatile.
It takes no arguments and therefore cannot be
overloaded.
It should have public access in the class declaration.

16
Class employee
{
Private :
Char name[20];
Int ecode ;
Char address[30];
Public :
Employee ( ); // constructor
~ Employee ( ); // destructor
Void getdata( );
Void display( );
};
17
18
#include<iostream>
#include<stdio>
Class account {
Private :
Float balance;
Float rate;
Public:
Account( ); // constructor name
~ account ( );// destructor name
Void deposit( );
Void withdraw( );
Void compound( );
Void getbalance( );
Void menu( );
}; //end of class definition
Account :: account( ) // constructor
{
Cout<<“enter the initial balancen”;
Cin>>balance;
}
Account :: ~account( ) // destructor
19
{
Cout<<“data base has been deletedn”
}
// to deposit
Void account ::deposit( )
{
Float amount;
Cout<<“how much amount want to deposit”;
Cin>>amount;
Balance=balace+amount ;
}
// the program is not complete , the purpose is to clear the function
of constructor and destructor
#include<iostream>
Using namespace std;
Int count =0;
Class alpha
{
Public :
Alpha()
{
Count ++;
Cout <<“n No. of object created “<<count;
}
~alpha()
{
20
Cout<<“n No. of object destroyed “<<count;
Count --;
}
};
Int main()
{ cout<<“n n Enter mainn”;
Alpha A1 A2 A3 A4;
{
Cout<<“nn Enter block 1n”;
Alpha A5;
}
{ cout<<“nn Enter Block 2 n”;
Alpha A6;
} 21
Cout<<“n n RE-enter Mainn”;
Return 0; Enter Block 2
No. of object created :5
} Re-Enter Main
No. of object destroyed
Output : Enter Main 4,3,2,1
No. of object created 1
No. of object created 2
No. of object created 3
No. of object created 4
Enter Block 1
No. ofobject created 5
No. of object Destroyed 5
22
Static Class Members
You can use the static keyword when declaring
class members
Static class members are somewhat different
from static variables
When you declare a class member to be static,
only one copy of that class member is created
during a program’s execution, regardless of how
many objects of the class you instantiate
Figure 7-38 illustrates the concept of the static
and non-static data members with the Payroll
class
23
Multiple Class Objects with
Static and Non-Static Data
Members
24
Static Data Members
You declare a static data member in your
implementation file using the syntax static
typename;, similar to the way you define a
static variable
static data members are bound by access
specifiers, the same as non-static data members
This means that public static data members
are accessible by anyone, whereas private
static data members are available only to other
functions in the class or to friend functions
25
Static Data Members
You could use a statement in the class constructor,
although doing so will reset a static variable’s value
to its initial value each time a new object of the class
is instantiated
Instead, to assign an initial value to a static data
member, you add a global statement to the
implementation file using the syntax type
class::variable=value;
Initializing a static data member at the global level
ensures that it is only initialized when a program first
executes—not each time you instantiate a new object
26
Static Data MembersFigure 7-39 contains an example of the Stocks class,
with the iStockCount static data member
Statements in the constructor and destructor
increment and decrement the iStockCount variable
each time a new Stocks object is created or destroyed
Figure 7-40 shows the program’s output
27
Static Data MembersYou can refer to a static data member by appending
its name and the member selection operator to any
instantiated object of the same class, using syntax such
as stockPick.iStockCount
By using the class name and the scope resolution
operator instead of any instantiated object of the class,
you clearly identify the data member as static
Figure 7-41 in the text shows an example of the Stocks
class program with the dPortfolioValue static data
member
The dPortfolioValue static data member is assigned
an initial value of 0 (zero) in the implementation file
28
Static Data Members
To add to the Estimator class a static data
member that stores the combined total of each
customer’s estimate, follow the instructions listed
on pages 403 and 404 of the textbook
29
Static Member FunctionsStatic member functions are useful for accessing
static data members
Like static data members, they can be accessed
independently of any individual class objects
This is useful when you need to retrieve the
contents of a static data member that is
declared as private
Static member functions are somewhat limited
because they can only access other static class
members or functions and variables located
outside of the class
30
Static Member Functions
You declare a static member function similar to
the way you declare a static data member-- by
preceding the function declaration in the interface
file with the static keyword
You do not include the static keyword in the
function definition in the implementation file
Like static data members, you need to call a
static member function’s name only from inside
another member function of the same class
31
Static Member Functions
You can execute static member functions even
if no object of a class is instantiated
One use of static member functions is to access
private static data members
To add to the Estimator class a static member
function that returns the value of the static
lCombinedCost data member, use the steps on
pages 405 and 406 of the textbook
32
Constant Objects
If you have any type of variable in a program that
does not change, you should always use the const
keyword to declare the variable as a constant
Constants are an important aspect of good
programming technique because they prevent
clients (or you) from modifying data that should
not change
Because objects are also variables, they too can be
declared as constants
33
Constant Objects
As with other types of data, you only declare an
object as constant if it does not change
Constant data members in a class cannot be
assigned values using a standard assignment
statement within the body of a member function
You must use an initialization list to assign initial
values to these types of data members
There is an example of this code shown on page
407 of the textbook
34
Constant Objects
Another good programming technique is to always
use the const keyword to declare get functions
that do not modify data members as constant
functions
The const keyword makes your programs more
reliable by ensuring that functions that are not
supposed to modify data cannot modify data
To define the Estimator class’s get functions as
constant, perform the procedures listed on page
408 of the textbook
35
Summary
The default constructor is the constructor that
does not include any parameters and that is called
for any declared objects of its class to which you
do not pass arguments
Initialization lists, or member initialization lists,
are another way of assigning initial values to a
class’s data members
A copy constructor is a special constructor that is
called when a new object is instantiated from an
old object
36
Summary
Operator overloading refers to the creation of
multiple versions of C++ operators that perform
special tasks required by the class in which an
overloaded operator function is defined
When you declare a class member to be static,
only one copy of that class member is created
during a program’s execution, regardless of how
many objects of the class you instantiate
37

More Related Content

What's hot

Data Structure and Algorithms Arrays
Data Structure and Algorithms ArraysData Structure and Algorithms Arrays
Data Structure and Algorithms ArraysManishPrajapati78
 
standard template library(STL) in C++
standard template library(STL) in C++standard template library(STL) in C++
standard template library(STL) in C++•sreejith •sree
 
CLASSES AND OBJECTS IN C++ +2 COMPUTER SCIENCE
CLASSES AND OBJECTS IN C++ +2 COMPUTER SCIENCECLASSES AND OBJECTS IN C++ +2 COMPUTER SCIENCE
CLASSES AND OBJECTS IN C++ +2 COMPUTER SCIENCEVenugopalavarma Raja
 
STACK ( LIFO STRUCTURE) - Data Structure
STACK ( LIFO STRUCTURE) - Data StructureSTACK ( LIFO STRUCTURE) - Data Structure
STACK ( LIFO STRUCTURE) - Data StructureYaksh Jethva
 
sparse matrix in data structure
sparse matrix in data structuresparse matrix in data structure
sparse matrix in data structureMAHALAKSHMI P
 
Constructor and Types of Constructors
Constructor and Types of ConstructorsConstructor and Types of Constructors
Constructor and Types of ConstructorsDhrumil Panchal
 
Vector class in C++
Vector class in C++Vector class in C++
Vector class in C++Jawad Khan
 
Doubly Linked List || Operations || Algorithms
Doubly Linked List || Operations || AlgorithmsDoubly Linked List || Operations || Algorithms
Doubly Linked List || Operations || AlgorithmsShubham Sharma
 
Arrays in Data Structure and Algorithm
Arrays in Data Structure and Algorithm Arrays in Data Structure and Algorithm
Arrays in Data Structure and Algorithm KristinaBorooah
 
13. Pointer and 2D array
13. Pointer  and  2D array13. Pointer  and  2D array
13. Pointer and 2D arrayGem WeBlog
 
Introduction to data structure
Introduction to data structureIntroduction to data structure
Introduction to data structureZaid Shabbir
 
Sql(structured query language)
Sql(structured query language)Sql(structured query language)
Sql(structured query language)Ishucs
 
Classes and data abstraction
Classes and data abstractionClasses and data abstraction
Classes and data abstractionHoang Nguyen
 
Union in C programming
Union in C programmingUnion in C programming
Union in C programmingKamal Acharya
 
class and objects
class and objectsclass and objects
class and objectsPayel Guria
 

What's hot (20)

Data Structure and Algorithms Arrays
Data Structure and Algorithms ArraysData Structure and Algorithms Arrays
Data Structure and Algorithms Arrays
 
standard template library(STL) in C++
standard template library(STL) in C++standard template library(STL) in C++
standard template library(STL) in C++
 
CLASSES AND OBJECTS IN C++ +2 COMPUTER SCIENCE
CLASSES AND OBJECTS IN C++ +2 COMPUTER SCIENCECLASSES AND OBJECTS IN C++ +2 COMPUTER SCIENCE
CLASSES AND OBJECTS IN C++ +2 COMPUTER SCIENCE
 
Arrays Basics
Arrays BasicsArrays Basics
Arrays Basics
 
C++ Arrays
C++ ArraysC++ Arrays
C++ Arrays
 
STACK ( LIFO STRUCTURE) - Data Structure
STACK ( LIFO STRUCTURE) - Data StructureSTACK ( LIFO STRUCTURE) - Data Structure
STACK ( LIFO STRUCTURE) - Data Structure
 
sparse matrix in data structure
sparse matrix in data structuresparse matrix in data structure
sparse matrix in data structure
 
Constructor and Types of Constructors
Constructor and Types of ConstructorsConstructor and Types of Constructors
Constructor and Types of Constructors
 
Vector class in C++
Vector class in C++Vector class in C++
Vector class in C++
 
Single linked list
Single linked listSingle linked list
Single linked list
 
Stacks in c++
Stacks in c++Stacks in c++
Stacks in c++
 
Array
ArrayArray
Array
 
Doubly Linked List || Operations || Algorithms
Doubly Linked List || Operations || AlgorithmsDoubly Linked List || Operations || Algorithms
Doubly Linked List || Operations || Algorithms
 
Arrays in Data Structure and Algorithm
Arrays in Data Structure and Algorithm Arrays in Data Structure and Algorithm
Arrays in Data Structure and Algorithm
 
13. Pointer and 2D array
13. Pointer  and  2D array13. Pointer  and  2D array
13. Pointer and 2D array
 
Introduction to data structure
Introduction to data structureIntroduction to data structure
Introduction to data structure
 
Sql(structured query language)
Sql(structured query language)Sql(structured query language)
Sql(structured query language)
 
Classes and data abstraction
Classes and data abstractionClasses and data abstraction
Classes and data abstraction
 
Union in C programming
Union in C programmingUnion in C programming
Union in C programming
 
class and objects
class and objectsclass and objects
class and objects
 

Viewers also liked

παραδοσιακα επαγγελματα
παραδοσιακα επαγγελματαπαραδοσιακα επαγγελματα
παραδοσιακα επαγγελματαlivaresi
 
Художественно - эстетическая кафедра
Художественно - эстетическая кафедра Художественно - эстетическая кафедра
Художественно - эстетическая кафедра Екатерина Шепелева
 
Consulting deck
Consulting deckConsulting deck
Consulting deckdCode
 
Bovee bct12 ppt_ch01
Bovee bct12 ppt_ch01Bovee bct12 ppt_ch01
Bovee bct12 ppt_ch01Samina Haider
 
30 kombi kullanımı
30 kombi kullanımı30 kombi kullanımı
30 kombi kullanımıKJHGTY
 
Data 101: The New World of Privacy & Security
Data 101: The New World of Privacy & SecurityData 101: The New World of Privacy & Security
Data 101: The New World of Privacy & SecurityQuarles & Brady
 
"Fundamentals 201: Transfers and Assignments in Franchising," ABA Forum on Fr...
"Fundamentals 201: Transfers and Assignments in Franchising," ABA Forum on Fr..."Fundamentals 201: Transfers and Assignments in Franchising," ABA Forum on Fr...
"Fundamentals 201: Transfers and Assignments in Franchising," ABA Forum on Fr...Quarles & Brady
 
Albert einstein slide
Albert einstein slideAlbert einstein slide
Albert einstein slideDavidLeTran
 
Informing the Mihai Eminescu Community
Informing the Mihai Eminescu CommunityInforming the Mihai Eminescu Community
Informing the Mihai Eminescu CommunityDoina Morari
 
Facebook education, Facebook Marketing
Facebook education, Facebook MarketingFacebook education, Facebook Marketing
Facebook education, Facebook Marketingmehergaje
 
Use and Protection of IP in Social Media and Apps
Use and Protection of IP in Social Media and AppsUse and Protection of IP in Social Media and Apps
Use and Protection of IP in Social Media and AppsQuarles & Brady
 
Get connected bender
Get connected benderGet connected bender
Get connected benderDoina Morari
 
Dhivya Darling's Birthday
Dhivya Darling's BirthdayDhivya Darling's Birthday
Dhivya Darling's BirthdayAkash Das
 
Clusters - Quayside Clothing Case Study
Clusters - Quayside Clothing Case StudyClusters - Quayside Clothing Case Study
Clusters - Quayside Clothing Case StudyClusters Ltd
 
Мой класс
Мой класс Мой класс
Мой класс Antshil
 

Viewers also liked (20)

παραδοσιακα επαγγελματα
παραδοσιακα επαγγελματαπαραδοσιακα επαγγελματα
παραδοσιακα επαγγελματα
 
Eloquent ORM
Eloquent ORMEloquent ORM
Eloquent ORM
 
Indian women in politics
 Indian women in politics Indian women in politics
Indian women in politics
 
Художественно - эстетическая кафедра
Художественно - эстетическая кафедра Художественно - эстетическая кафедра
Художественно - эстетическая кафедра
 
Consulting deck
Consulting deckConsulting deck
Consulting deck
 
Operations mgt
Operations mgtOperations mgt
Operations mgt
 
Bovee bct12 ppt_ch01
Bovee bct12 ppt_ch01Bovee bct12 ppt_ch01
Bovee bct12 ppt_ch01
 
Slides book-download
Slides book-downloadSlides book-download
Slides book-download
 
30 kombi kullanımı
30 kombi kullanımı30 kombi kullanımı
30 kombi kullanımı
 
Data 101: The New World of Privacy & Security
Data 101: The New World of Privacy & SecurityData 101: The New World of Privacy & Security
Data 101: The New World of Privacy & Security
 
"Fundamentals 201: Transfers and Assignments in Franchising," ABA Forum on Fr...
"Fundamentals 201: Transfers and Assignments in Franchising," ABA Forum on Fr..."Fundamentals 201: Transfers and Assignments in Franchising," ABA Forum on Fr...
"Fundamentals 201: Transfers and Assignments in Franchising," ABA Forum on Fr...
 
Albert einstein slide
Albert einstein slideAlbert einstein slide
Albert einstein slide
 
Informing the Mihai Eminescu Community
Informing the Mihai Eminescu CommunityInforming the Mihai Eminescu Community
Informing the Mihai Eminescu Community
 
Facebook education, Facebook Marketing
Facebook education, Facebook MarketingFacebook education, Facebook Marketing
Facebook education, Facebook Marketing
 
Use and Protection of IP in Social Media and Apps
Use and Protection of IP in Social Media and AppsUse and Protection of IP in Social Media and Apps
Use and Protection of IP in Social Media and Apps
 
Get connected bender
Get connected benderGet connected bender
Get connected bender
 
Dhivya Darling's Birthday
Dhivya Darling's BirthdayDhivya Darling's Birthday
Dhivya Darling's Birthday
 
Clusters - Quayside Clothing Case Study
Clusters - Quayside Clothing Case StudyClusters - Quayside Clothing Case Study
Clusters - Quayside Clothing Case Study
 
Мой класс
Мой класс Мой класс
Мой класс
 
Hybrid variety of plants
Hybrid variety of plantsHybrid variety of plants
Hybrid variety of plants
 

Similar to Constructor,destructors cpp

Constructors in C++.pptx
Constructors in C++.pptxConstructors in C++.pptx
Constructors in C++.pptxRassjb
 
chapter-9-constructors.pdf
chapter-9-constructors.pdfchapter-9-constructors.pdf
chapter-9-constructors.pdfstudy material
 
CONSTRUCTORS IN C++ +2 COMPUTER SCIENCE
CONSTRUCTORS IN C++ +2 COMPUTER SCIENCECONSTRUCTORS IN C++ +2 COMPUTER SCIENCE
CONSTRUCTORS IN C++ +2 COMPUTER SCIENCEVenugopalavarma Raja
 
Tutconstructordes
TutconstructordesTutconstructordes
TutconstructordesNiti Arora
 
Constructor and Destructor.pdf
Constructor and Destructor.pdfConstructor and Destructor.pdf
Constructor and Destructor.pdfMadnessKnight
 
constructors and destructors
constructors and destructorsconstructors and destructors
constructors and destructorsAkshaya Parida
 
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 desturctor
Constructor and desturctorConstructor and desturctor
Constructor and desturctorSomnath Kulkarni
 
Constructors & Destructors [Compatibility Mode].pdf
Constructors & Destructors [Compatibility Mode].pdfConstructors & Destructors [Compatibility Mode].pdf
Constructors & Destructors [Compatibility Mode].pdfLadallaRajKumar
 
data Structure Lecture 1
data Structure Lecture 1data Structure Lecture 1
data Structure Lecture 1Teksify
 
Constructors and destructors in C++
Constructors and destructors in  C++Constructors and destructors in  C++
Constructors and destructors in C++RAJ KUMAR
 
CONSTRUCTORS, DESTRUCTORS AND OPERATOR OVERLOADING.pptx
CONSTRUCTORS, DESTRUCTORS AND OPERATOR OVERLOADING.pptxCONSTRUCTORS, DESTRUCTORS AND OPERATOR OVERLOADING.pptx
CONSTRUCTORS, DESTRUCTORS AND OPERATOR OVERLOADING.pptxDeepasCSE
 
Constructors and Destructors
Constructors and DestructorsConstructors and Destructors
Constructors and DestructorsKeyur Vadodariya
 
Introductions to Constructors.pptx
Introductions to Constructors.pptxIntroductions to Constructors.pptx
Introductions to Constructors.pptxSouravKrishnaBaul
 

Similar to Constructor,destructors cpp (20)

Constructors in C++.pptx
Constructors in C++.pptxConstructors in C++.pptx
Constructors in C++.pptx
 
chapter-9-constructors.pdf
chapter-9-constructors.pdfchapter-9-constructors.pdf
chapter-9-constructors.pdf
 
CONSTRUCTORS IN C++ +2 COMPUTER SCIENCE
CONSTRUCTORS IN C++ +2 COMPUTER SCIENCECONSTRUCTORS IN C++ +2 COMPUTER SCIENCE
CONSTRUCTORS IN C++ +2 COMPUTER SCIENCE
 
Tutconstructordes
TutconstructordesTutconstructordes
Tutconstructordes
 
Constructors and destructors
Constructors and destructorsConstructors and destructors
Constructors and destructors
 
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 in object oriented program.pptx
constructor in object oriented program.pptxconstructor in object oriented program.pptx
constructor in object oriented program.pptx
 
Constructors and Destructor in C++
Constructors and Destructor in C++Constructors and Destructor in C++
Constructors and Destructor in C++
 
Constructor and desturctor
Constructor and desturctorConstructor and desturctor
Constructor and desturctor
 
Constructors & Destructors [Compatibility Mode].pdf
Constructors & Destructors [Compatibility Mode].pdfConstructors & Destructors [Compatibility Mode].pdf
Constructors & Destructors [Compatibility Mode].pdf
 
Class and object C++.pptx
Class and object C++.pptxClass and object C++.pptx
Class and object C++.pptx
 
Constructor and destructor in C++
Constructor and destructor in C++Constructor and destructor in C++
Constructor and destructor in C++
 
Constructors and destructors in C++ part 2
Constructors and destructors in C++ part 2Constructors and destructors in C++ part 2
Constructors and destructors in C++ part 2
 
data Structure Lecture 1
data Structure Lecture 1data Structure Lecture 1
data Structure Lecture 1
 
Constructors and destructors in C++
Constructors and destructors in  C++Constructors and destructors in  C++
Constructors and destructors in C++
 
Constructor
ConstructorConstructor
Constructor
 
CONSTRUCTORS, DESTRUCTORS AND OPERATOR OVERLOADING.pptx
CONSTRUCTORS, DESTRUCTORS AND OPERATOR OVERLOADING.pptxCONSTRUCTORS, DESTRUCTORS AND OPERATOR OVERLOADING.pptx
CONSTRUCTORS, DESTRUCTORS AND OPERATOR OVERLOADING.pptx
 
Constructors and Destructors
Constructors and DestructorsConstructors and Destructors
Constructors and Destructors
 
Introductions to Constructors.pptx
Introductions to Constructors.pptxIntroductions to Constructors.pptx
Introductions to Constructors.pptx
 

More from रमन सनौरिया (8)

Marketing book for po and clerk
Marketing book for po and clerkMarketing book for po and clerk
Marketing book for po and clerk
 
Adolf hitler ebook
Adolf hitler ebookAdolf hitler ebook
Adolf hitler ebook
 
Acoustic guitar book
Acoustic guitar bookAcoustic guitar book
Acoustic guitar book
 
Mobile sniffer project
Mobile sniffer projectMobile sniffer project
Mobile sniffer project
 
Jawalamuki project
Jawalamuki projectJawalamuki project
Jawalamuki project
 
product = people
product = peopleproduct = people
product = people
 
THE PR
THE PRTHE PR
THE PR
 
1. intro to comp & c++ programming
1. intro to comp & c++ programming1. intro to comp & c++ programming
1. intro to comp & c++ programming
 

Recently uploaded

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
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajanpragatimahajan3
 
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
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 
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
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpinRaunakKeshri1
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...fonyou31
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
The byproduct of sericulture in different industries.pptx
The byproduct of sericulture in different industries.pptxThe byproduct of sericulture in different industries.pptx
The byproduct of sericulture in different industries.pptxShobhayan Kirtania
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesFatimaKhan178732
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docxPoojaSen20
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 

Recently uploaded (20)

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...
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajan
 
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
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
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
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpin
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
The byproduct of sericulture in different industries.pptx
The byproduct of sericulture in different industries.pptxThe byproduct of sericulture in different industries.pptx
The byproduct of sericulture in different industries.pptx
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and Actinides
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docx
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 

Constructor,destructors cpp

  • 1. ObjectivesIn this chapter you will learn: About default constructors How to create parameterized constructors How to work with initialization lists How to create copy constructors 1
  • 2. Advanced Constructors Constructors can do more than initialize data members They can execute member functions and perform other types of initialization routines that a class may require when it first starts 2
  • 3. Default Constructors The default constructor does not include parameters, and is called for any declared objects of its class to which you do not pass arguments Remember that you define and declare constructor functions the same way you define other functions, although you do not include a return type because constructor functions do not return values 3
  • 4. Constructor Function 4 A Constructor is a special member function whose task is to initialize the object of its class. It is special because it name is same as 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.
  • 5. Default Constructors The constructor function in Figure is an example of a default constructor In addition to initializing data members and executing member functions, default constructors perform various types of behind-the-scenes class maintenance 5
  • 6. Simple Program 6 // default constructor #include<iostream> Using namespace std; Class integer { Int m,n; Public: Integer(void); // constructor declared Void getinfo( ); }; Integer :: integer void( ) // constructor defined { m= 0; n=0; }
  • 7. Parameterized Constructors The constructor integer( ) define above initialize the data members of all the objects to zero. However is practice it may be necessary to initialize the various data elements of different objects with different values, when they are created. A parameterized constructor allows a client to pass initialization values to your class during object instantiation Instead of assigning default values, you can allow a client to pass in the value for these data members by designing the constructor function with parameters. 7
  • 8. 8 Class integer { Int m, n; Public : Integer (int x, int y); }; Integer :: integer(int x,int y) { m= x; n=y; } By Calling the Constructor explicitly By Calling the consructor implicitly
  • 9.  integer int1 = integer(0,100); Explicitly called Integer int1(0,100) Implicitly called. Shorthand method. 9
  • 10. Copy Constructor There will be times when you want to instantiate a new object based on an existing object C++ uses a copy constructor to exactly copy each of the first object’s data members into the second object’s data members in an operation known as member wise copying A copy constructor is a special constructor that is called when a new object is instantiated from an old object 10
  • 11. Copy Constructor The syntax for a copy constructor declaration is class_name :: class_name (class_name &ptr) The Copy Constructor may be used in the following format also using a const keyword. class_name :: class_name (const class_name & ptr) Copy Constructor are always used when the compiler has to create a temporary object of a class object.The copy constructor are used in the following situations:- The Initialization of an object by another object of the same class. Return of object as a function value. Stating the object as by value parameters of a function. 11
  • 12. Copy Constructor Example with Program //fibonacci series using copy constructor #include<iostream> Using namespaces std ; Class fibonacci { Private : Unsigned long int f0,f1,fib; Public : Fiboancci () // constructor { F0=0; F1=1; Fib=f0+f1; } Fibonacci (fibonacci &ptr) // copy construtor { F0=ptr.f0; F1=ptr.f1; Fib=prt.fib; } 12 Void increment ( ) { F0=f1; F1=fib; Fib=f0+f1; } Void display ( ) { Cout<<fib<<‘/t’; } }; Void main( ) { Fibonacci number ; For(int i=0;i<=15;++i) { Number.display(); Number.increment(); } }
  • 13. #include<iostream> void display (void) Using namespace std ; { cout<<id; Class code // class name } { }; Int id; int main() Public : { Code() code A(100);//object A is created // constructor name same as class name code B(A); // copy const. called { code C= A; // CC called again } code D; // D is created, not intilized Code(int a ) { // constructor again D=A; // C C not called Id=a; cout<<“n” id of A:=A.display(); } cout<<“n” id of B:=B.display(); Code (code &x) // copy constuctor cout<<“n” id of C:=C.display(); { id=x.id; // copy in the value cout<<“n” id of D:=D.display(); } return 0; } 13
  • 14. Destructors Just as a default constructor is called when a class object is first instantiated, a default destructor is called when the object is destroyed A default destructor cleans up any resources allocated to an object once the object is destroyed The default destructor is sufficient for most classes, except when you have allocated memory on the heap 14
  • 15. Destructors You create a destructor function using the name of the class, the same as a constructor A destructor is commonly called in two ways: When a stack object loses scope because the function in which it is declared ends When a heap object is destroyed with the delete operator 15
  • 16. Syntax rules for writing a dectructor function : A destructor function name is the same as that of the class it belongs except that the first character of the name must be a tilde ( ~). It is declared with no return types ( not even void) since it cannot even return a value. It cannot de declared static ,const or volatile. It takes no arguments and therefore cannot be overloaded. It should have public access in the class declaration.  16
  • 17. Class employee { Private : Char name[20]; Int ecode ; Char address[30]; Public : Employee ( ); // constructor ~ Employee ( ); // destructor Void getdata( ); Void display( ); }; 17
  • 18. 18 #include<iostream> #include<stdio> Class account { Private : Float balance; Float rate; Public: Account( ); // constructor name ~ account ( );// destructor name Void deposit( ); Void withdraw( ); Void compound( ); Void getbalance( ); Void menu( ); }; //end of class definition Account :: account( ) // constructor { Cout<<“enter the initial balancen”; Cin>>balance; } Account :: ~account( ) // destructor
  • 19. 19 { Cout<<“data base has been deletedn” } // to deposit Void account ::deposit( ) { Float amount; Cout<<“how much amount want to deposit”; Cin>>amount; Balance=balace+amount ; } // the program is not complete , the purpose is to clear the function of constructor and destructor
  • 20. #include<iostream> Using namespace std; Int count =0; Class alpha { Public : Alpha() { Count ++; Cout <<“n No. of object created “<<count; } ~alpha() { 20
  • 21. Cout<<“n No. of object destroyed “<<count; Count --; } }; Int main() { cout<<“n n Enter mainn”; Alpha A1 A2 A3 A4; { Cout<<“nn Enter block 1n”; Alpha A5; } { cout<<“nn Enter Block 2 n”; Alpha A6; } 21
  • 22. Cout<<“n n RE-enter Mainn”; Return 0; Enter Block 2 No. of object created :5 } Re-Enter Main No. of object destroyed Output : Enter Main 4,3,2,1 No. of object created 1 No. of object created 2 No. of object created 3 No. of object created 4 Enter Block 1 No. ofobject created 5 No. of object Destroyed 5 22
  • 23. Static Class Members You can use the static keyword when declaring class members Static class members are somewhat different from static variables When you declare a class member to be static, only one copy of that class member is created during a program’s execution, regardless of how many objects of the class you instantiate Figure 7-38 illustrates the concept of the static and non-static data members with the Payroll class 23
  • 24. Multiple Class Objects with Static and Non-Static Data Members 24
  • 25. Static Data Members You declare a static data member in your implementation file using the syntax static typename;, similar to the way you define a static variable static data members are bound by access specifiers, the same as non-static data members This means that public static data members are accessible by anyone, whereas private static data members are available only to other functions in the class or to friend functions 25
  • 26. Static Data Members You could use a statement in the class constructor, although doing so will reset a static variable’s value to its initial value each time a new object of the class is instantiated Instead, to assign an initial value to a static data member, you add a global statement to the implementation file using the syntax type class::variable=value; Initializing a static data member at the global level ensures that it is only initialized when a program first executes—not each time you instantiate a new object 26
  • 27. Static Data MembersFigure 7-39 contains an example of the Stocks class, with the iStockCount static data member Statements in the constructor and destructor increment and decrement the iStockCount variable each time a new Stocks object is created or destroyed Figure 7-40 shows the program’s output 27
  • 28. Static Data MembersYou can refer to a static data member by appending its name and the member selection operator to any instantiated object of the same class, using syntax such as stockPick.iStockCount By using the class name and the scope resolution operator instead of any instantiated object of the class, you clearly identify the data member as static Figure 7-41 in the text shows an example of the Stocks class program with the dPortfolioValue static data member The dPortfolioValue static data member is assigned an initial value of 0 (zero) in the implementation file 28
  • 29. Static Data Members To add to the Estimator class a static data member that stores the combined total of each customer’s estimate, follow the instructions listed on pages 403 and 404 of the textbook 29
  • 30. Static Member FunctionsStatic member functions are useful for accessing static data members Like static data members, they can be accessed independently of any individual class objects This is useful when you need to retrieve the contents of a static data member that is declared as private Static member functions are somewhat limited because they can only access other static class members or functions and variables located outside of the class 30
  • 31. Static Member Functions You declare a static member function similar to the way you declare a static data member-- by preceding the function declaration in the interface file with the static keyword You do not include the static keyword in the function definition in the implementation file Like static data members, you need to call a static member function’s name only from inside another member function of the same class 31
  • 32. Static Member Functions You can execute static member functions even if no object of a class is instantiated One use of static member functions is to access private static data members To add to the Estimator class a static member function that returns the value of the static lCombinedCost data member, use the steps on pages 405 and 406 of the textbook 32
  • 33. Constant Objects If you have any type of variable in a program that does not change, you should always use the const keyword to declare the variable as a constant Constants are an important aspect of good programming technique because they prevent clients (or you) from modifying data that should not change Because objects are also variables, they too can be declared as constants 33
  • 34. Constant Objects As with other types of data, you only declare an object as constant if it does not change Constant data members in a class cannot be assigned values using a standard assignment statement within the body of a member function You must use an initialization list to assign initial values to these types of data members There is an example of this code shown on page 407 of the textbook 34
  • 35. Constant Objects Another good programming technique is to always use the const keyword to declare get functions that do not modify data members as constant functions The const keyword makes your programs more reliable by ensuring that functions that are not supposed to modify data cannot modify data To define the Estimator class’s get functions as constant, perform the procedures listed on page 408 of the textbook 35
  • 36. Summary The default constructor is the constructor that does not include any parameters and that is called for any declared objects of its class to which you do not pass arguments Initialization lists, or member initialization lists, are another way of assigning initial values to a class’s data members A copy constructor is a special constructor that is called when a new object is instantiated from an old object 36
  • 37. Summary Operator overloading refers to the creation of multiple versions of C++ operators that perform special tasks required by the class in which an overloaded operator function is defined When you declare a class member to be static, only one copy of that class member is created during a program’s execution, regardless of how many objects of the class you instantiate 37