Ticker

6/recent/ticker-posts

CONSTRUCTORS AND DESTRUCTORS IN C++

    

C++ provides a special member function called the constructor which enables an object to initialize itself when it is created. This is known as automatic initialization of objects. It also provides another member function called the destructor that destroys the objects when they are no longer required.

CONSTRUCTORS

A constructor is a 'special' member function whose task is to initialize the objects of its class. It is special because its name is same as the class name. The constructor is invoked whenever an object of its associated class is created. It is called constructor because it construct the value data members of the class. 
//class with a constructor 
class Integer 
            int m, n; 
        public: 
            Integer(void); / constructor declared ... 
}; 
Integer :: Integer(void) // constructor defined 
        m = 0; n = 0; 
}; 

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. 

Integer int1; // object int1 created 

not only creates the object int1 of type Integer but also initializes its data members m and n to 0.There is no need to write any statement to invoke the constructor function.

A constructor that accepts no parameters is called the default constructor. The default constructor for class A is A::A(). If no such constructor is defined the compiler suppliers default constructor. Therefore a statement such as 

        A a; 

invokes the default constructor of the compiler to create the object a. The constructor functions have some special characteristics. 

They should be declared in the public section. 

They are invoked automatically when the objects are created. 

They do not have return types, not even void and therefore, they cannot return values. 

They cannot be inherited, though a derived class can call the base class constructor. 

Like other C++ functions, they can have default arguments. 

Constructors cannot be virtual. 

We cannot refer to their addresses. 

An object with a constructor (or destructor) cannot be used as a member of a union. 

They make implicit calls to the operations new and delete when memory allocation is required. Remember, when a constructor is declared for a class initialization of the class objects become mandatory.

PARAMETERIZED CONSTRUCTORS

The constructor Integer(), defined above, initialized 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 they 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 arguments are called parameterized constructors. 

The constructor integer() may be modified to take arguments as shown below : 

class integer 

            int m, n; 

        public: 

            integer (int x, int y); //parameterized constructor 
            .......

}; 

integer : : integer int x, int y) 

m = x; n = y; 

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

        integer int1;

may not work. We must pass the initial values as arguments to the constructor function when an object is declared. This can be done in two ways; 

By calling the constructor explicitly. 

By calling the constructor implicitly. 

        Integer Int1 = Integer (0, 100); //explicit call 

This statement creates in integer object int1 and passes the values 0 and 100 to it. 

The second is implemented as follows : 

Integer int1 (0, 100); //implicit call. 

This method sometimes called the shorthand method, is used very often as it is shorter, looks better and is easy to implement.

 MULTIPLE CONSTRUCTORS IN A CLASS

So far we have used two kinds of constructors. They are; 

        integer(); // No arguments 

        integer(int, int); // Two arguments 

In the first case, the constructor itself supplies the data values and no values are passed by the calling program. In the second case, the function call passes the appropriate values from main ( ). C++ permits us to use both these constructors in the same class. For example, we could define a class as follows : 

class integer 

            int m, n; 
        public: 
            integer ( ) {m = 0; n = 0;) // constructor 1 
            integer (int a, int b) {m = a; n = b;) // constructor 2 
            integer (integer & i) {m = i.m; n = i.n;) // constructor 3 
}; 

This declared three constructors for an integer object. The first constructor receives no arguments, the second receives two arguments and the third receives one integer object as an argument. For example, the declaration. 

            Integer I1; 

would automatically invoke the first constructor and set both m and n of I1 to zero. The statement 

            integer l2 (20, 40); 

would call the second constructor which will initialize the data members m and n I2 to 20 and 40 respectively. Finally, the statement. 

            Integer I3(I2); 

would invoke the third constructor which copies the values of I2 into I3. That is, it sets the value of every data element of I2 to the value of the corresponding data element of I3. As mentioned earlier, such a constructor is called the copy constructor. The process of sharing the same name by two or more functions is referred to as function overloading. Similarly, when more than one constructor is overloaded, it is called constructor overloading. 

CONSTRUCTORS WITH DEFAULT ARGUMENTS

It is possible to define constructors with default arguments. For example, the constructor complex ( ) can be declared as follows. 

            complex (float real, float image = 0) 

The default value of the argument image is zero. Then the statement 

            complex C (5, 0): 

assigns the value 5.0 to the real variable and 0.0 to image (by default). However, the statement 

            complex C(2.0, 3.0); 

assigns 2.0 to real and 3.0 to image. The actual parameter, when specified, overrides the default value. As pointed out earlier, the missing arguments must be the trailing ones. 

It is important to distinguish between the default constructor A::A() and the default argument constructor A::A(int = 0). The default argument constructor can be called with either one argument or no arguments. When called with no arguments, it becomes a default constructor. When both these forms are used in a class it causes ambiguity.

DYNAMIC INITIALIZATION OF OBJECTS

Class objects can be initialized dynamically too. That is the initial value of an object may be provided during run time. One advantage of dynamic initialization is that we can provide various initialization formats, using overloaded constructors. This provides the flexibility of using different format of data at run time depending upon the situation. 

Consider the long term deposit schemes working in the commercial banks. The banks provide different interest rates for different schemes a well as for different periods of investment. 

COPY CONSTRUCTOR

We used the copy constructor. 

            Integer (integer & I) 

in section 3.4 as one of the overloaded constructors. 

As stated earlier, a copy constructor is used to declare and initialize an object from another object For example, the statement. 

                integer l2 (l1); 

would define the object I2 and at the same time initialize to the values of I1. Another form of this statement is 

            integer l2 = l1; 

The process of initializing through a copy constructor is known as copy initialization. Remember the statement. 

        l2 = l1; 

will not invoke the copy constructor. However, if I1 and I2 are objects, this statement is legal simply assigns the values of I1 to I2, member-by- member.

A copy constructor takes a reference to an object of the same class s itself as an argument.

DESTRUCTORS

A destructor, as the name implies, is used to destroy the objects that have been created by a constructor. Like a constructor, it 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: 

~ integer ( ) { } 

A destructor never takes any argument nor does it return any value. It will be invoked implicitly by the compiler upon exit from the program (or block or function as the case may be) to clean up storage that is no longer accessible. It is good practice to declare destructors in a program since it release memory space for future use 

Whenever new is used to allocate memory in the constructors, we should use delete to free that memory. For example the destructor for the matrix class discussed above may be defined as follows.

        matrix :: ~ matrix ( ) 
        
                for (int i = 0: j < d1;i++) 
                    delete p[i]; 
                delete p; 
        

This is required because when the pointers to object go out of scope, a destructor is not called implicitly. 

The example below illustrates that the destructor has been implicitly by the compiler.

ALSO SEARCH:

"constructors and destructors in C++"

"what is constructor and destructor in C++ with example"

"constructors and destructors in C++ with programming examples"

"what are the constructors and destructors"

"characteristics of constructors and destructors in C++"

"constructors and destructors in C++"

"copy constructor in c++"

"c++ constructor"

"dynamic constructor in c++"

"what is parameterized constructor in c++"

"constructor and destructor in c++"

"types of constructor"