SlideShare una empresa de Scribd logo
1 de 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

Más contenido relacionado

La actualidad más candente

Functions in c language
Functions in c language Functions in c language
Functions in c language tanmaymodi4
 
Constructors and destructors
Constructors and destructorsConstructors and destructors
Constructors and destructorsVineeta Garg
 
Constructor and Types of Constructors
Constructor and Types of ConstructorsConstructor and Types of Constructors
Constructor and Types of ConstructorsDhrumil Panchal
 
Union in C programming
Union in C programmingUnion in C programming
Union in C programmingKamal Acharya
 
Pointers and Dynamic Memory Allocation
Pointers and Dynamic Memory AllocationPointers and Dynamic Memory Allocation
Pointers and Dynamic Memory AllocationRabin BK
 
Pointers in c
Pointers in cPointers in c
Pointers in cMohd Arif
 
Constructor and Destructor PPT
Constructor and Destructor PPTConstructor and Destructor PPT
Constructor and Destructor PPTShubham Mondal
 
Vector class in C++
Vector class in C++Vector class in C++
Vector class in C++Jawad Khan
 
Class and object in C++
Class and object in C++Class and object in C++
Class and object in C++rprajat007
 

La actualidad más candente (20)

Functions in c language
Functions in c language Functions in c language
Functions in c language
 
Pointer in C++
Pointer in C++Pointer in C++
Pointer in C++
 
Constructors and destructors
Constructors and destructorsConstructors and destructors
Constructors and destructors
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
 
Constructor and Types of Constructors
Constructor and Types of ConstructorsConstructor and Types of Constructors
Constructor and Types of Constructors
 
User defined functions
User defined functionsUser defined functions
User defined functions
 
Union in C programming
Union in C programmingUnion in C programming
Union in C programming
 
Constructor and destructor
Constructor  and  destructor Constructor  and  destructor
Constructor and destructor
 
This pointer
This pointerThis pointer
This pointer
 
Pointer to function 1
Pointer to function 1Pointer to function 1
Pointer to function 1
 
Pointers in c++
Pointers in c++Pointers in c++
Pointers in c++
 
Pointers and Dynamic Memory Allocation
Pointers and Dynamic Memory AllocationPointers and Dynamic Memory Allocation
Pointers and Dynamic Memory Allocation
 
Pointers in c
Pointers in cPointers in c
Pointers in c
 
Function in c
Function in cFunction in c
Function in c
 
Constructor and Destructor PPT
Constructor and Destructor PPTConstructor and Destructor PPT
Constructor and Destructor PPT
 
Functions in C
Functions in CFunctions in C
Functions in C
 
Vector class in C++
Vector class in C++Vector class in C++
Vector class in C++
 
Class and object in C++
Class and object in C++Class and object in C++
Class and object in C++
 
Control statements in c
Control statements in cControl statements in c
Control statements in c
 
C pointers
C pointersC pointers
C pointers
 

Destacado

παραδοσιακα επαγγελματα
παραδοσιακα επαγγελματαπαραδοσιακα επαγγελματα
παραδοσιακα επαγγελματα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
 

Destacado (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 a 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 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
 
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
 

Similar a 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 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
 
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)
 
Tut Constructor
Tut ConstructorTut Constructor
Tut Constructor
 

Más de रमन सनौरिया (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
 

Último

Congestive Cardiac Failure..presentation
Congestive Cardiac Failure..presentationCongestive Cardiac Failure..presentation
Congestive Cardiac Failure..presentationdeepaannamalai16
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxHumphrey A Beña
 
ROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxVanesaIglesias10
 
Dust Of Snow By Robert Frost Class-X English CBSE
Dust Of Snow By Robert Frost Class-X English CBSEDust Of Snow By Robert Frost Class-X English CBSE
Dust Of Snow By Robert Frost Class-X English CBSEaurabinda banchhor
 
How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17Celine George
 
Measures of Position DECILES for ungrouped data
Measures of Position DECILES for ungrouped dataMeasures of Position DECILES for ungrouped data
Measures of Position DECILES for ungrouped dataBabyAnnMotar
 
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...JojoEDelaCruz
 
Millenials and Fillennials (Ethical Challenge and Responses).pptx
Millenials and Fillennials (Ethical Challenge and Responses).pptxMillenials and Fillennials (Ethical Challenge and Responses).pptx
Millenials and Fillennials (Ethical Challenge and Responses).pptxJanEmmanBrigoli
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxAnupkumar Sharma
 
4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptxmary850239
 
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfInclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfTechSoup
 
4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptx4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptxmary850239
 
4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptxmary850239
 
Transaction Management in Database Management System
Transaction Management in Database Management SystemTransaction Management in Database Management System
Transaction Management in Database Management SystemChristalin Nelson
 
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfVirtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfErwinPantujan2
 
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...Postal Advocate Inc.
 
Active Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdfActive Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdfPatidar M
 
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSJoshuaGantuangco2
 
Expanded definition: technical and operational
Expanded definition: technical and operationalExpanded definition: technical and operational
Expanded definition: technical and operationalssuser3e220a
 

Último (20)

Congestive Cardiac Failure..presentation
Congestive Cardiac Failure..presentationCongestive Cardiac Failure..presentation
Congestive Cardiac Failure..presentation
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
 
ROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptx
 
Paradigm shift in nursing research by RS MEHTA
Paradigm shift in nursing research by RS MEHTAParadigm shift in nursing research by RS MEHTA
Paradigm shift in nursing research by RS MEHTA
 
Dust Of Snow By Robert Frost Class-X English CBSE
Dust Of Snow By Robert Frost Class-X English CBSEDust Of Snow By Robert Frost Class-X English CBSE
Dust Of Snow By Robert Frost Class-X English CBSE
 
How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17
 
Measures of Position DECILES for ungrouped data
Measures of Position DECILES for ungrouped dataMeasures of Position DECILES for ungrouped data
Measures of Position DECILES for ungrouped data
 
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
 
Millenials and Fillennials (Ethical Challenge and Responses).pptx
Millenials and Fillennials (Ethical Challenge and Responses).pptxMillenials and Fillennials (Ethical Challenge and Responses).pptx
Millenials and Fillennials (Ethical Challenge and Responses).pptx
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
 
4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx
 
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfInclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
 
4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptx4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptx
 
4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx
 
Transaction Management in Database Management System
Transaction Management in Database Management SystemTransaction Management in Database Management System
Transaction Management in Database Management System
 
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfVirtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
 
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
 
Active Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdfActive Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdf
 
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
 
Expanded definition: technical and operational
Expanded definition: technical and operationalExpanded definition: technical and operational
Expanded definition: technical and operational
 

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