Category: Concepts of Constructors and Destructors in C++

Interested in learning C Programming? Click here...


Destructors in Cpp 0

Destructors in C++

A destructor in C++, as the name implies, is used to destroy the objects that have been created by a constructor. Like a constructor, the destructor in C++ is a member function whose name is the same as the class name but is preceded by a tilde (~). For example, the destructor for the class integer can be defined as shown below:

A destructor in C++ never takes any arguments nor does it return any value. It will be invoked implicitly by the compiler upon exit from the program (or the block or the function as the case may...

Constructor with Default Arguments in Cpp 0

Constructor with Default Arguments in C++

It is possible in C++ to define constructors with default arguments. For example, the constructor integer(), defined in the previous section (Constructors in C++), can be defined as follows:

The default value of the argument y is 3. Thus, the statement:

assigns the value 1 to x variable and 3 to y (by default). However, the statement:

assigns 1 to x and 5 to y. The actual parameters, when specified, overrides the default value. Note: The missing arguments must be the trailing ones.


Parameterized Constructors in Cpp 0

Parameterized Constructors in C++

The constructor integer(), defined in the previous section (Constructors in C++), initializes the data members of all the objects to zero. However, in practice it may be necessary to initialize the various data elements of different objects with different values when the are created. C++ permits us to achieve this objective by passing arguments to the constructor function when the objects are created. The constructors that can take the arguments are called parameterized constructors. The constructor integer() may be modified to take arguments as shown below:

When a constructor has been parameterized, the object declaration statement such as:

...

Constructors in Cpp 2

Constructors in C++

A constructor in C++ is a special member function whose task is to initialize the objects of its class. It is special because its name is the same as the 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. A constructor is declared and defined as follows:

When a class contains a constructor like the one defined above, it is guaranteed that an object created by the class will be initialized automatically. For example, the declaration:

not...