Constructors and Destructors in C++

By: Daniel Malcolm Emailed: 1786 times Printed: 2614 times    

Latest comments
By: rohit kumar - how this program is work
By: Kirti - Hi..thx for the hadoop in
By: Spijker - I have altered the code a
By: ali mohammed - why we use the java in ne
By: ali mohammed - why we use the java in ne
By: mizhelle - when I exported the data
By: raul - no output as well, i'm ge
By: Rajesh - thanx very much...
By: Suindu De - Suppose we are executing

There are two ways to define an integer variable. You can define the variable and then assign a value to it later in the program. For example,

int Weight;            // define a variable
...                    // other code here
Weight = 7;            // assign it a value

Or you can define the integer and immediately initialize it. For example,

int Weight = 7;        // define and initialize to 7

Initialization combines the definition of the variable with its initial assignment. Nothing stops you from changing that value later. Initialization ensures that your variable is never without a meaningful value.

How do you initialize the member data of a class? Classes have a special member function called a constructor. The constructor can take parameters as needed, but it cannot have a return value--not even void. The constructor is a class method with the same name as the class itself.

Whenever you declare a constructor, you'll also want to declare a destructor. Just as constructors create and initialize objects of your class, destructors clean up after your object and free any memory you might have allocated. A destructor always has the name of the class, preceded by a tilde (~). Destructors take no arguments and have no return value. Therefore, the Cat declaration includes


Default Constructors and Destructors

If you don't declare a constructor or a destructor, the compiler makes one for you. The default constructor and destructor take no arguments and do nothing.

What good is a constructor that does nothing? In part, it is a matter of form. All objects must be constructed and destructed, and these do-nothing functions are called at the right time. However, to declare an object without passing in parameters, such as

Cat Rags;           // Rags gets no parameters

you must have a constructor in the form


When you define an object of a class, the constructor is called. If the Cat constructor took two parameters, you might define a Cat object by writing

Cat Frisky (5,7);

If the constructor took one parameter, you would write

Cat Frisky (3);

In the event that the constructor takes no parameters at all, you leave off the parentheses and write

Cat Frisky ;

This is an exception to the rule that states all functions require parentheses, even if they take no parameters. This is why you are able to write

Cat Frisky;

which is a call to the default constructor. It provides no parameters, and it leaves off the parentheses. You don't have to use the compiler-provided default constructor. You are always free to write your own constructor with no parameters. Even constructors with no parameters can have a function body in which they initialize their objects or do other work.

As a matter of form, if you declare a constructor, be sure to declare a destructor, even if your destructor does nothing. Although it is true that the default destructor would work correctly, it doesn't hurt to declare your own. It makes your code clearer.

Program below rewrites the Cat class to use a constructor to initialize the Cat object, setting its age to whatever initial age you provide, and it demonstrates where the destructor is called.

Using constructors and destructors.

1:   // Demonstrates declaration of a constructors and
2:   // destructor for the Cat class
4:   #include <iostream.h>      // for cout
6:   class Cat                   // begin declaration of the class
7:   {
8:    public:                    // begin public section
9:      Cat(int initialAge);     // constructor
10:     ~Cat();                  // destructor
11:     int GetAge();            // accessor function
12:     void SetAge(int age);    // accessor function
13:     void Meow();
14:   private:                   // begin private section
15:     int itsAge;              // member variable
16:  };
18:  // constructor of Cat,
19:  Cat::Cat(int initialAge)
20:  {
21:     itsAge = initialAge;
22:  }
24:  Cat::~Cat()                 // destructor, takes no action
25:  {
26:  }
28:  // GetAge, Public accessor function
29:  // returns value of itsAge member
30:  int Cat::GetAge()
31:  {
32:     return itsAge;
33:  }
35:  // Definition of SetAge, public
36:  // accessor function
38:  void Cat::SetAge(int age)
39:  {
40:     // set member variable its age to
41:     // value passed in by parameter age
42:     itsAge = age;
43:  }
45:  // definition of Meow method
46:  // returns: void
47:  // parameters: None
48:  // action: Prints "meow" to screen
49:  void Cat::Meow()
50:  {
51:     cout << "Meow.\n";
52:  }
54:  // create a cat, set its age, have it
55   // meow, tell us its age, then meow again.
56:  int main()
57:  {
58:    Cat Frisky(5);
59:    Frisky.Meow();
60:    cout << "Frisky is a cat who is " ;
61:    cout << Frisky.GetAge() << " years old.\n";
62:    Frisky.Meow();
63:    Frisky.SetAge(7);
64:    cout << "Now Frisky is " ;
65:    cout << Frisky.GetAge() << " years old.\n";
66;     return 0;
67: }

Output: Meow.
Frisky is a cat who is 5 years old.
Now Frisky is 7 years old.

Analysis: The above program adds a constructor that takes an integer. Line 10 declares the destructor, which takes no parameters. Destructors never take parameters, and neither constructors nor destructors return a value--not even void.
Lines 19-22 show the implementation of the constructor. It is similar to the implementation of the SetAge() accessor function. There is no return value.

Lines 24-26 show the implementation of the destructor ~Cat(). This function does nothing, but you must include the definition of the function if you declare it in the class declaration.

Line 58 contains the definition of a Cat object, Frisky. The value 5 is passed in to Frisky's constructor. There is no need to call SetAge(), because Frisky was created with the value 5 in its member variable itsAge, as shown in line 61. In line 63, Frisky's itsAge variable is reassigned to 7. Line 65 prints the new value.


DO use constructors to initialize your objects. DON'T give constructors or destructors a return value. DON'T give destructors parameters.

C++ Home | All C++ Tutorials | Latest C++ Tutorials

Sponsored Links

If this tutorial doesn't answer your question, or you have a specific question, just ask an expert here. Post your question to get a direct answer.

Bookmark and Share


1. View Comment

you're so great!

View Tutorial          By: renz at 2008-08-10 18:29:59
2. View Comment

Nice explaination of constructor and destructor. But also give diffrenc between costructor and destructor.

View Tutorial          By: Anon at 2009-03-01 03:50:06
3. View Comment

It is working. Thank u dear!!!

View Tutorial          By: Ashwani Rana at 2009-04-02 03:56:17
4. View Comment

All in all is not a a question How 2 use contstuctor and distructors.can you write for me maybe 5 simple programs using constructors and destructors

View Tutorial          By: Tkalani at 2009-06-03 02:16:14
5. View Comment

You are good work ,an axplane is so gread
thanks friends

View Tutorial          By: chetan at 2009-06-08 11:58:51
6. View Comment


View Tutorial          By: KUSUM at 2010-02-02 23:48:50
7. View Comment

its nice.. thank you so much.........

View Tutorial          By: rozen at 2010-04-14 11:21:07
8. View Comment

nice example's

View Tutorial          By: karthi at 2011-01-30 02:25:36
9. View Comment

gr8 work :)

View Tutorial          By: ahmad at 2011-03-23 01:05:57
10. View Comment

the default construrctor does not give the defalut value when we execute a program ???give me the true solution?

View Tutorial          By: muhammad abdullah at 2011-04-11 13:16:20
11. View Comment

Good work. Although it would be nicer if you can possibly increase the number of exemplary programs instead of just one.

View Tutorial          By: frisked09 at 2011-05-26 23:52:34
12. View Comment

thank u its a clear information .i got the solutions for my doubts.once again thank you daer

View Tutorial          By: anand at 2011-06-29 09:30:12
13. View Comment

oh u solved my one of the hardest problem through this program and its awsum explanation iam very thankful 2 u god bless u

View Tutorial          By: zehra at 2012-01-28 19:44:14
14. View Comment

meow is simple and awesome

View Tutorial          By: vishnu prasanth at 2013-01-10 10:00:35

Your name (required):

Your email(required, will not be shown to the public):

Your sites URL (optional):

Your comments:

More Tutorials by Daniel Malcolm
javac options in Java
Operator Precedence in Java
Calling Multiple Listeners in JSF
Using free() Function in C
ForwardAction in Struts
Listing Files and Directories sample program in C
Binary Tree - (Self-referential Structures) example program in C
A simple program using EL in JSP
Command-line Arguments in C
Example Calculator program in C - describing use of External Variables in C
Assignment Operators and Expressions in C
The for statement in C
JSF Basics
assert() Versus Exceptions in C++
RMS Basics in J2ME

More Tutorials in C++
Two-Dimensional Array Manipulation in C++
Calculate average using Two-Dimensional Array in C++
Compute the square root of the sum of the squares of an array in C++
Matrix using nested for loops in C++
Sorting an array of Strings in C++
Calculating total based on the given quantity and price in C++
Compiling and Linking Multiple Source Files in C++
Enumerations in C++
Program to add two numbers in C++
Comments in C++
while loop in C++
for loop in C++
Programming errors a compiler will detect in C++
if in C++
Using the Built-in Arithmetic Types in C++

More Latest News
Most Viewed Articles (in C++ )
Using cout.width() in C++
Calculating total based on the given quantity and price in C++
Difference between Procedural, Structured, and Object-Oriented Programming
Dot (.) vs Arrow (->) to access data members in C++
Constructors and Destructors in C++
Calculate average using Two-Dimensional Array in C++
C++ Recursion function explained using Fibonacci series
assert() example program in C++
cin.ignore() in C++
Using peek() and putback() with cin in C++
Programming errors a compiler will detect in C++
Multiple statements in for loops in C++
Using Comments in a C++ Program
Using cout in C++
Sorting an array of Strings in C++
Most Emailed Articles (in C++)
Using cout.width() in C++
Two-Dimensional Array Manipulation in C++
Sorting an array of Strings in C++
Using cout in C++
Printing values in DEBUG mode in C++
File in C++ - Writing text to a file in C++
while loop in C++
Interface Versus Implementation in C++
C++ Sample Program for Allocating, using, and deleting pointers.
How to handle Exceptions in C++
Multiple inheritance example in C++
Vector variables in C++
Using the Built-in Arithmetic Types in C++
Compute the square root of the sum of the squares of an array in C++
Getting Started with C++