Constructors

Constructors
Constructors

CONCEPT

 A constructor is a member function that is automatically called when a class object is created.

EXPLANATION

A constructor is a special public member function that is automatically called to construct a class object when it is created. If the programmer does not write a constructor, C++ automatically provides one. You never see it, but it runs silently in the background each time your program defines an object. Often, however, programmers write their own constructor when they create a class. If they do this, in addition to constructing each newly created object of the class, it will execute whatever code the programmer has included in it. Most often programmers use a constructor to initialize an object’s member variables. However, it can do anything a normal function can do.

A constructor looks like a regular function except that its name must be the same as  natheme of the class it is a part of. This is how the compiler knows that a particular member function is a constructor. Also, the constructor must have no return type. In the end  a program includes a class called Demo with a constructor that does nothing except print a message. It was written this way to demonstrate when the constructor executes. Because the Demo object is created between two cout statements, the constructor will print its message between the output lines produced by those two statements. 

PROGRAM
1 // This program demonstrates when a constructor executes.
2 #include <iostream>
3 using namespace std;
4
5 class Demo
6 {
7 public:
8 Demo() // Constructor
9 {
10 cout << "Now the constructor is running.\n";
11 }
12 };
13
14 int main()
15 {
16 cout << "This is displayed before the object is created.\n";
17
18 Demo demoObj; // Define a Demo object
19
20 cout << "This is displayed after the object is created.\n";
21 return 0;

22 }
Program Output
This is displayed before the object is created.
Now the constructor is running.
This is displayed after the object is created.

In the above Program the constructor was defined as an inline function inside the class declaration. As with all class member functions, a constructor can be written either as an inline function (if it is short enough), or can have just its prototype placed in the class declaration and be defined outside the class. In this case, as you recall, its name must be preceded by the name of the class the function belongs to and the scope resolution operator. Because the name of the constructor function is the same as the class name, the same name appears twice. Here is how the function header for the Demo constructor would look if it had been defined outside the class.
Demo::Demo() // Constructor
{
cout << "Now the constructor is running.\n";
}

Previous
Next Post »