SlideShare uma empresa 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

Mais conteúdo relacionado

Mais procurados

Memory Management C++ (Peeling operator new() and delete())
Memory Management C++ (Peeling operator new() and delete())Memory Management C++ (Peeling operator new() and delete())
Memory Management C++ (Peeling operator new() and delete())Sameer Rathoud
 
Operator overloading
Operator overloadingOperator overloading
Operator overloadingBurhan Ahmed
 
Structure in c language
Structure in c languageStructure in c language
Structure in c languagesangrampatil81
 
C Pointers
C PointersC Pointers
C Pointersomukhtar
 
Class and object in C++
Class and object in C++Class and object in C++
Class and object in C++rprajat007
 
Virtual base class
Virtual base classVirtual base class
Virtual base classTech_MX
 
Pointers in c
Pointers in cPointers in c
Pointers in cMohd Arif
 
classes and objects in C++
classes and objects in C++classes and objects in C++
classes and objects in C++HalaiHansaika
 
Two dimensional array
Two dimensional arrayTwo dimensional array
Two dimensional arrayRajendran
 
Call by value or call by reference in C++
Call by value or call by reference in C++Call by value or call by reference in C++
Call by value or call by reference in C++Sachin Yadav
 
Programming Fundamentals Functions in C and types
Programming Fundamentals  Functions in C  and typesProgramming Fundamentals  Functions in C  and types
Programming Fundamentals Functions in C and typesimtiazalijoono
 
Presentation on C++ Programming Language
Presentation on C++ Programming LanguagePresentation on C++ Programming Language
Presentation on C++ Programming Languagesatvirsandhu9
 
Function in c program
Function in c programFunction in c program
Function in c programumesh patil
 

Mais procurados (20)

Memory Management C++ (Peeling operator new() and delete())
Memory Management C++ (Peeling operator new() and delete())Memory Management C++ (Peeling operator new() and delete())
Memory Management C++ (Peeling operator new() and delete())
 
Built in function
Built in functionBuilt in function
Built in function
 
Functions in c++
Functions in c++Functions in c++
Functions in c++
 
Managing I/O in c++
Managing I/O in c++Managing I/O in c++
Managing I/O in c++
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
 
Structure in c language
Structure in c languageStructure in c language
Structure in c language
 
C Pointers
C PointersC Pointers
C Pointers
 
Class and object in C++
Class and object in C++Class and object in C++
Class and object in C++
 
2- Dimensional Arrays
2- Dimensional Arrays2- Dimensional Arrays
2- Dimensional Arrays
 
Constructors and Destructor in C++
Constructors and Destructor in C++Constructors and Destructor in C++
Constructors and Destructor in C++
 
Virtual base class
Virtual base classVirtual base class
Virtual base class
 
Pointers in c
Pointers in cPointers in c
Pointers in c
 
classes and objects in C++
classes and objects in C++classes and objects in C++
classes and objects in C++
 
Two dimensional array
Two dimensional arrayTwo dimensional array
Two dimensional array
 
Call by value or call by reference in C++
Call by value or call by reference in C++Call by value or call by reference in C++
Call by value or call by reference in C++
 
Programming Fundamentals Functions in C and types
Programming Fundamentals  Functions in C  and typesProgramming Fundamentals  Functions in C  and types
Programming Fundamentals Functions in C and types
 
OOP C++
OOP C++OOP C++
OOP C++
 
Presentation on C++ Programming Language
Presentation on C++ Programming LanguagePresentation on C++ Programming Language
Presentation on C++ Programming Language
 
Function in c program
Function in c programFunction in c program
Function in c program
 
Function C programming
Function C programmingFunction C programming
Function C programming
 

Destaque

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

Destaque (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
 

Semelhante 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 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
 
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
 

Semelhante 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 in object oriented program.pptx
constructor in object oriented program.pptxconstructor in object oriented program.pptx
constructor in object oriented program.pptx
 
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)
 

Mais 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

ACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfSpandanaRallapalli
 
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfAMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfphamnguyenenglishnb
 
Choosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for ParentsChoosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for Parentsnavabharathschool99
 
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Celine George
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...JhezDiaz1
 
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
 
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.
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...Nguyen Thanh Tu Collection
 
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfJemuel Francisco
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPCeline George
 
Science 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptxScience 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptxMaryGraceBautista27
 
ENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomnelietumpap1
 
Culture Uniformity or Diversity IN SOCIOLOGY.pptx
Culture Uniformity or Diversity IN SOCIOLOGY.pptxCulture Uniformity or Diversity IN SOCIOLOGY.pptx
Culture Uniformity or Diversity IN SOCIOLOGY.pptxPoojaSen20
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Celine George
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 
Karra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxKarra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxAshokKarra1
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 

Último (20)

ACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdf
 
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfAMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
 
Choosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for ParentsChoosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for Parents
 
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptxYOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
 
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
 
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
 
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...
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
 
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERP
 
Science 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptxScience 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptx
 
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptxFINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
 
ENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choom
 
Culture Uniformity or Diversity IN SOCIOLOGY.pptx
Culture Uniformity or Diversity IN SOCIOLOGY.pptxCulture Uniformity or Diversity IN SOCIOLOGY.pptx
Culture Uniformity or Diversity IN SOCIOLOGY.pptx
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 
Karra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxKarra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptx
 
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptxLEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 

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