Está en la página 1de 8

1/27/13

C++ Classes Constructors and destructors | CodingUnit Programming Tutorials

Home About
Search

rss posts

C++ Classes Constructors and destructors


In the last C++ tutorial we looked at the basic concept of classes. In this C++ programming tutorial we take another look at classes.

Constructor and Destructor


Classes can have complicated internal structures, so object initialization and clean-up of a class is much more complicated then for any other data structures. Constructors and destructors are special member functions of classes that are used to construct and destroy class objects. The construction can be for example: initialization for objects or memory allocation. The destruction may involve de-allocation of memory or other clean-up for objects. Constructors and destructors are declared within a class declaration (as like any other member function). A constructor or a destructor can be defined in-line or external to the class declaration. We may declare some default arguments when we make a constructor. There are some restrictions that apply to constructors and destructors: Constructors and destructors cannot have a return type (not even void). Pointers and references cannot be used on constructors and destructors (It is not possible to get there address) Constructors and destructors cannot be declared static, const or volatile. Constructors cannot be declared with the keyword virtual. Note: the same access rules apply to constructors and destructors as with any other member function. Constructors are called automatically by the compiler when defining class objects. The destructors are called when a class object goes out of scope. So lets take a look at an example:
# i n c l u d e < i o s t r e a m > u s i n gn a m e s p a c es t d ; c l a s sC A d d { p u b l i c : i n to n e ; C A d d ( i n tt w o ) { c o u t< <" Ac o n s t r u c t o ri sc a l l e d "< <e n d l ; o n e = t w o ; } C A d d ( ) { c o u t< <" Ad e f a u l tc o n s t r u c t o ri sc a l l e d"< <e n d l ; } ~ C A d d ( ) { c o u t< <" D e s t r u c t i n g"< <o n e< <e n d l ;
www.codingunit.com/cplusplus-tutorial-classes-constructors-and-destructors 1/8

1/27/13

C++ Classes Constructors and destructors | CodingUnit Programming Tutorials

} i n ta d d ( ) { r e t u r n ( o n e + o n e ) ; } } ; i n tm a i n ( ) { C A d dm y o b j 1 ( 4 ) ; C A d dm y o b j 2 ; c o u t< <m y o b j 1 . o n e< <e n d l ; c o u t< <" E n t e ran u m b e r:"; c i n> >m y o b j 2 . o n e ; c o u t< <m y o b j 2 . a d d ( )< <e n d l ; r e t u r n ( 0 ) ; }

Note: with CAdd myobj2; we did not use any parentheses because we want to call the default constructor. Putting the parentheses behind myobj2 will result in an error. The statement :
C A d d ( i n tt w o ) { c o u t< <" Ac o n s t r u c t o ri sc a l l e d "< <e n d l ; o n e = t w o ; }

declares the constructor of the class CAdd. The name of the constructor is the same as the name of the class. If statement CAdd myobject(4) is called this constructor is called (because of the number between the parentheses in myobject(). (The compiler will call the constructor whose parameters match the arguments used in the function call.) The statement :
C A d d ( ) { c o u t< <" Ad e f a u l tc o n s t r u c t o ri sc a l l e d"< <e n d l ; }

declares a default constructor. If the statement CAdd myobj2; is called the default constructor is called (note: no number between the parentheses. (Remember, the compiler will call the constructor whose parameters match the arguments used in the function call.) The statement :
~ C A d d ( ) { c o u t< <" D e s t r u c t i n g"< <o n e< <e n d l ; }

declares a destructor to deallocate the objects. Note the tilde (~). At the end of the program objects are deallocated in the reverse order in which the constructors are called.

www.codingunit.com/cplusplus-tutorial-classes-constructors-and-destructors

2/8

1/27/13

C++ Classes Constructors and destructors | CodingUnit Programming Tutorials

Note:Constructors cannot be called explicitly as if they were regular member functions. They are only executed when a new object of that class is created. Destructors are automatically called when an object is destroyed. For example when an object is dynamically assigned and it is released using the delete operator. (Destructors are really handy when you use dynamic memory).

Pointers to classes
Pointer can also be used with classes. (A class becomes a valid type once declared). Take a look at the example:
C A d d*p t r _ a d d ;

Now ptr_add is a pointer to an object of class CAdd. As we did with structures we can use the arrow operator (->) of indirection to refer to a member of an object pointed by a pointer. Take a look at an example:
# i n c l u d e < i o s t r e a m > u s i n gn a m e s p a c es t d ; c l a s sC A d d { p r i v a t e : i n tx ,y ; p u b l i c : v o i da d d ( i n t , i n t ) ; i n tr e t ( ){r e t u r nx + y ;} } ; v o i dC A d d : : a d d ( i n ta ,i n tb ) { x=a ; y=b ; } i n tm a i n ( ) { C A d dm y _ o b j e c t ,* p t r _ a d d ; p t r _ a d d =n e wC A d d ; m y _ o b j e c t . a d d ( 4 , 4 ) ; p t r _ a d d > a d d ( 2 , 2 ) ; c o u t< <m y _ o b j e c t . r e t ( )< <e n d l ; c o u t< <p t r _ a d d > r e t ( )< <e n d l ; r e t u r n0 ; }

In the table below you can read some pointer and class operators:
E x p r e s s i o n * a p o i n t e db y a a d d r e s so f a m e m b e rbo fo b j e c t E x p l a n a t i o n

& a

www.codingunit.com/cplusplus-tutorial-classes-constructors-and-destructors

3/8

1/27/13
a . b a

C++ Classes Constructors and destructors | CodingUnit Programming Tutorials

a > b

m e m b e rbo fo b j e c t p o i n t e db ya m e m b e rbo fo b j e c t p o i n t e db ya( s a m ea st h ep r e v i o u so n e ) f i r s to b j e c tp o i n t e d b ya s e c o n do b j e c tp o i n t e d b ya ( n + 1 ) t ho b j e c tp o i n t e d b ya

( * a ) . b

a [ 0 ]

a [ 1 ]

a [ n ]

Be sure that you understand the logic of all of these expressions before proceeding with the next tutorial. That is all for this tutorial.
This entry was posted in C++ Tutorials. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site. Tweet This! or use ShareThis to share this post with others.

There are currently 7 responses to C++ Classes Constructors and destructors


Why not let us know what you think by adding your own comment! 1. Rugnar on March 6th, 2010: Please, give example for usage of destructor. 2. admin on March 6th, 2010: @Rugnar, below you will find an example as requested: #include <iostream> using namespace std; // A class CRectArea with a constructor and descructor // to determine the area of a rectangle. class CRectArea { int *width, *height; public: CRectArea (int,int); ~CRectArea (); int areaofrect () { return (*width * *height); } }; // Constructor CRectArea::CRectArea (int x, int y) { //Dynamically allocate some memory width = new int; height = new int; *width = x; *height = y; www.codingunit.com/cplusplus-tutorial-classes-constructors-and-destructors
4/8

1/27/13

C++ Classes Constructors and destructors | CodingUnit Programming Tutorials

*height = y; } // Destructor CRectArea::~CRectArea () { //Delete the allocate memory delete width; delete height; } int main () { CRectArea myrectangle (2,2); cout << The area of the rectangle is: << myrectangle.areaofrect() << endl; return 0; } In this example we want to determine the area of a rectangle. We use a constructor, where we dynamically allocate some memory for the width and height. In the destructor we delete the memory, we dynamically allocated in the constructor. Now, every time an instance of a class is created the constructor method is called (in this case: CRectArea myrectangle (2,2); The destructor is called near the end of the program. Where are destructors commonly used for? They are usually used to clean up when an object is no longer necessary, to clean up the mess you have create during a program. Hope this helps, good luck! 3. Crazy on August 13th, 2010: Hi, Can you please explain copy constructor and its usage Thanks in advance 4. admin on August 14th, 2010: @Crazy We working on a tutorial to explain copy constructor and assignment operators. Give us a couple of days to come-up with some examples. 5. mebrahten on December 6th, 2011: it is nice note 6. ajay kumar on June 19th, 2012: Hey, Hi Admin..! I am Student of BCA and till date i was not able to understand this C or C++ but i just saw your website and the contents and honestly speaking man..! Hats off 2 u..! Coz Tday i got to know bout so many things which were der in my syllbus but aah nevaa uncdersttod coz of stupid faculties in mah colg.! Thankzz Man..! Dam Awesome Site..! ***** Complete deserving 5x* Site..! 7. admin on June 27th, 2012: hi.. i m student.. what is the reason of pointer concept used in c .and c++ does not use?? and y in c++ used in constructing/destructing?

Leave a Reply:
www.codingunit.com/cplusplus-tutorial-classes-constructors-and-destructors 5/8

1/27/13

C++ Classes Constructors and destructors | CodingUnit Programming Tutorials

Name (required) Mail (will not be published) (required) Website

Submit Comment

go back up to content

C++ Tutorials
History of the C++ language C++ Compilers (GNU and Visual Studio) First C++ program, hello world C++ Variables and Data Types C++ constants, escape codes and strings C++ operators, compound assignments C++ Standard I/O cin and cout C++ Standard I/O and strings C++ The if statement and switch statement C++ for loops, while loops C++ Using functions, function parameters C++ Functions and command-line parameters C++ arrays, arrays and loops C++ Character sequence using arrays C++ pointers reference and dereference operators C++ Dynamic Memory C++ structures, typedef and unions C++ Classes C++ Classes Constructors and destructors File IO in C++ (text and binary files) File IO in C++ (text and binary files) part II C++ Tutorial Namespaces and anonymous namespaces C++ Overloading and Operator Overloading C++ Unary and binary operator overloading and static members C++ Inheritance C++ Friend function and Friend class C++ Templates C++ Polymorphism and Abstract Base Class C++ Exceptions and exception handling C++ Typecasting Part 1 C++ Typecasting Part 2 RTTI, dynamic_cast, typeid and type_info C++ Preprocessor Directives
www.codingunit.com/cplusplus-tutorial-classes-constructors-and-destructors 6/8

1/27/13

C++ Classes Constructors and destructors | CodingUnit Programming Tutorials

C++ Binary Operator Overloading Greater or Less than

Polymorph Screening
www.solidformsolutions.co.uk

Our typical screen is designed to identify the most solid forms

Latest Posts
C Tutorial Splitting a Text File into Multiple Files C Tutorial Deleting a Record from a Binary File C Tutorial Call by Value or Call by Reference Checking for Palindrome Strings or Numbers in C Language Linear Search Algorithm in C Language Determining the Area of Different Shaped Triangles in C Area of a Rectangle Circle and Trapezium in C How to Print Floyds Triangle in C Printing a Diamond Pattern in C PHP Tutorial File Handling

new ad compain
www.ecp.com

www.ecp.com www.ecp.com

www.codingunit.com/cplusplus-tutorial-classes-constructors-and-destructors

7/8

1/27/13
PLC based Process Control
w w w .PakPLC.com Siemens, Allen Bradley, Mitsubishi Industrial Automation Solutions

C++ Classes Constructors and destructors | CodingUnit Programming Tutorials

Forcheck
w w w .forcheck.nl The ultimate Fortran analyser Can you affort not to use Forcheck?

visual basic 6.0


w w w .w inw rap.net/scripting/component Basic language end-user scripting for Window s 32/64b NET Applications

Free optimization tool.


w w w .jmodelica.org Python and Modelica based tool for dynamic optimization. Try now .

2013 CodingUnit Programming Tutorials. All Rights Reserved. | Contact TERMS and Privacy Policy UNDER WHICH THIS SERVICE IS PROVIDED TO YOU.

www.codingunit.com/cplusplus-tutorial-classes-constructors-and-destructors

8/8

También podría gustarte