Thursday, October 8, 2015

Chapter 10 - Constructors and Destructors


LETS LEARN

WHAT IS A CONSTRUCTOR

     Use of Constructor

     Implementing a Constructor

WHAT IS A DESTRUCTOR

     Use of Destructor

     Implementing a Destructor

OVERLOADING CONSTRUCTORS

DEFAULT CONSTRUCTOR

WHAT IS A CONSTRUCTOR

constructor is the special method (member-function) of a class that is automatically executed whenever a new object is created of that class.

A constructor will have the same name as that of the class and it does not have any return value (not even void).

Syntax to declare a constructor:


class-name (argument-list);


Syntax to define a constructor:


class-name :: class-name (argument-list)   

     {          

             // Body of the constructor function

     }

Objects generally need to initialize variables or assign dynamic memory during their process of creation to become operative and to avoid returning unexpected values during their execution. From what we learned in Chapter 9 (Object Oriented Programming) Programs 56 & 57, if we called the area() before having called the set_value() we would have got some unknown result since the members x and y would not have been assigned a value. In order to avoid that, a class can include a special function called constructor, which is automatically called whenever a new object of this class is created.

Use of Constructor


The constructor is most often used by programmers to initialize the Objects to default values (or certain desired values) at the time of object creation. This ensures that Objects created for a certain task contain certain important preset values. The constructor is also used to assign dynamic memory during their process of creation.

Implementing a Constructor

We are going to implement constructor into the class CRectangle (refer to PROGRAM 56).

 

PROGRAM 61

Q. Write a program using Constructors to find the area of 2 Rectangles using one Class & two of its Objects.

 

#include <iostream>

using namespace std;

class CRectangle                   //CLASS declaration

{

    int width, height;

    public:

    CRectangle (int, int);       // Constructor declaration

    int area ()

        {

          return (width*height);

        }

};

CRectangle::CRectangle (int a, int b)    // Constructor definition

{

     width = a;

     height = b;

}

main ()

{

  CRectangle rect (3,4);             // Constructor initialization

  CRectangle rectb (5,6);          // Constructor initialization

  cout << "Area of Rectangle from Object rect  : " << rect.area() << endl;

  cout << "Area of Rectangle from Object rectb : " << rectb.area() << endl;

}


Output


 Area of Rectangle from Object rect   : 12 .

 Area of Rectangle from Object rectb : 30 . . .

If you remember PROGRAM 56 of last Chapter on OOPs, we had used setValue() to assign the values of width & height of rectangle by calling rect.setValue (3, 4); from main()

However, in the above program we have not used the setValue(), instead we have the constructor function CRectangle (int a, int b) that performs a similar action: it initializes the values of width and height with the parameters that are passed to it from main() namely:


CRectangle rect (3,4);

CRectangle rectb (5,6);

 

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. You can also notice that the constructor does not have a return value - not even void.


WHAT IS A DESTRUCTOR

A destructor is the special method (member function) of a class that is automatically executed when an object is destroyed. An object is destroyed when:

1.  its scope of existence has finished (for example, if it was defined as a local object within a function and the function ends) or

2.   it is a dynamically assigned object and is released using the operator delete.

The destructor has same name as that of the class, has to be preceded with a tilde sign (~) and has no return value.


Use of Destructor

The use of destructor is helpful when several Objects are dynamically created and their purpose gets over. In such a case, unwanted memory usage can be avoided by destroying (deallocating or releasing) the memory occupied by an Object using the Destructor method.

Implementing a Destructor

Let’s implement constructor and destructor in a program and find out how it works.


PROGRAM 62


Q. Write a program using Constructor and Destructor to find the area of 2 Rectangles using one Class & two of its Objects.


#include <iostream>

using namespace std;

class CRectangle                      // CLASS declaration

{

    int *width, *height;

    public:

    CRectangle (int, int);           // Constructor declaration

    ~CRectangle ();                  //  Destructor declaration

    int area ()

                 {

                     return (*width *  *height);  // (*width X *height)

                  }  

};

CRectangle::CRectangle (int a, int b)   // Constructor definition

{

  width = new int;

  height = new int;

  *width = a;

  *height = b;

}

CRectangle::~CRectangle ()                // Destructor definition

{

  delete width;

  delete height;

}

main ()

{

  CRectangle rect (3,4), rectb (5,6);    // Constructor initialization

  cout<<"Area of Rectangle from Object rect  : " << rect.area() << endl;

  cout<<"Area of Rectangle from Object rectb : " << rectb.area() << endl;

}



Output


 Area of Rectangle from Object rect   : 12 .

 Area of Rectangle from Object rectb : 30 .



 

OVERLOADING CONSTRUCTORS


Do you remember function overloading where a single function was redefined multiple times (with different parameters & return types) so that it could be reused to perform different tasks? That was function overloading.


Like any other function, a constructor can be overloaded with more than one task by redefining the constructor multiple times and passing it with different parameters. This is constructor overloading. Remember that for overloaded functions, the compiler will call that function whose parameters match the arguments used in the function call. In the case of constructors (which are automatically called when an object is created) the exact function that is executed, is the one that matches the arguments passed in the object declaration.


PROGRAM 63

 

Q. Write a program using Constructor Overloading to find the area of 2 Rectangles using one Class & two of its Objects.


#include <iostream>

using namespace std;

class CRectangle                            // CLASS declaration

{

int width, height;

public:

CRectangle ();                             // Constructor declaration

CRectangle (int, int);                 // Constructor declaration (Overloaded)

int area (void) {return (width*height);}

};

CRectangle::CRectangle ()    // Constructor definition

{

width = 5;

height = 5;

}

CRectangle::CRectangle (int a, int b) // Constructor definition (Overloaded)

{

width = a;

height = b;

}

main ()

{

 CRectangle rect (3,4); // Constructor initialization (Overloaded)

 CRectangle rectb;       // Constructor initialization (Overloaded)

 cout << "Area of Rectangle from Object rect  : " << rect.area() << endl;

 cout << "Area of Rectangle from Object rectb : " << rectb.area() << endl;

}

OUTPUT

 Area of Rectangle from Object rect   : 12 

 Area of Rectangle from Object rectb : 25 .


In the above program, notice how rectb object was declared without passing any parameters. So, it was initialized with the constructor that has no parameters, which in turn initializes both width and height with a value of 5.

Important: Notice that, when we declare a new object and we want to use its default constructor (without parameters), we do not include parentheses.

CRectangle rectb;   // right

CRectangle rectb(); // wrong!


DEFAULT CONSTRUCTOR


Regarding Constructors, the C++ compiler always:


1. creates a default constructor for you if you do not specify your own.

2. provides three special member functions in total that are implicitly declared if you do not declare your own: copy constructorcopy assignment operator, and default destructor.


 The copy constructor is a constructor which is executed when a new object is created from an already existing object (as a copy of the existing object).

The assignment operator creates a copy of values from an existing object and assigns it to another initialized object.


The copy constructor and the copy assignment operator copies all the data contained in another object (the constructor explicitly declared by you) to the data members of the current object (default constructor). For the class CExample, the copy constructor implicitly declared by the compiler would be something similar to:

CExample::CExample (const CExample &rv)

{

 a=rv.a;  b=rv.b;  c=rv.c;

}

 

 

Note: Here, rv is the reference variable to the address of explicit constructor CExample. Value of variable a in rv is assigned to variable a in default constructor, similarly b and c are assigned.

 

 

Therefore, the two following object declarations are correct:


CExample ex (2,3);

CExample ex2 (ex);   // copy constructor (data copied from ex)


No comments:

Post a Comment