Wednesday, 2 February 2022

Q. 5. Why do we need to use constructor ? explain with suitable examples.


 

Q. 5. Why do we need to use constructor ? explain with suitable examples. 

 

Sol. 

A constructor is a special type of member function that is called automatically when an object is created.


There are the following reasons to use constructors:


>We use constructors to initialize the object with the default or initial state. The default values for primitives may not be what are you looking for.

>Another reason to use constructor is that it informs about dependencies. In other words, using the constructor, we can request the user of that class for required dependencies.

>We can find out what it needs in order to use this class, just by looking at the constructor.


In short, we use the constructor to initialize the instance variable of the class.


Example 1: C++ Default Constructor

// C++ program to demonstrate the use of default constructor


#include <iostream>

using namespace std;


// declare a class

class  Wall {

  private:

    double length;


  public:

    // default constructor to initialize variable

    Wall() {

      length = 5.5;

      cout << "Creating a wall." << endl;

      cout << "Length = " << length << endl;

    }

};


int main() {

  Wall wall1;

  return 0;

}

__-----_--------_----_-------------------------------

Output


Creating a Wall

Length = 5.5


xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx


Example 2: C++ Parameterized Constructor

// C++ program to calculate the area of a wall


#include <iostream>

using namespace std;


// declare a class

class Wall {

  private:

    double length;

    double height;


  public:

    // parameterized constructor to initialize variables

    Wall(double len, double hgt) {

      length = len;

      height = hgt;

    }


    double calculateArea() {

      return length * height;

    }

};


int main() {

  // create object and initialize data members

  Wall wall1(10.5, 8.6);

  Wall wall2(8.5, 6.3);


  cout << "Area of Wall 1: " << wall1.calculateArea() << endl;

  cout << "Area of Wall 2: " << wall2.calculateArea();


  return 0;

}

--------------------------------------------------

Output


Area of Wall 1: 90.3

Area of Wall 2: 53.55


,...,..,........................,.................................



No comments:

Post a Comment