Constructors in C++

A constructor, as its name implies, is used to create (construct) objects. It's like any another function but with exceptions -
A constructor is always associated with a class and this function does not return anything and thus it does not have any return type associated with it.
It is used only for aiding in creation of objects. Let's look at how a normal function looks:

// this function has a return type of 'int'
int add(int a, int b) {
 return a + b;
}

Name of the function is add, its return type is int (i.e it returns an integer after it is done with its operations) and it takes in two parameters - a and b.
Now, let's say we have a Box class and for creating a Box we need to follow some steps, we cannot just create one out of nothing. For example, we cannot create a Box without the required width and height obviously! Here's how a constructor for the Box class might look like:

class Box {
public:
 // Box is the name of the constructor function
 // ITS NAME IS ALWAYS THE SAME AS ITS CLASS NAME
 // Since, a constructor function does not return anything,
 // it does not have a return type before its name
 Box(int width, int height) {
  // this constructor takes width and height

  /*
  Possible steps to make a Box object

  1.  Get a cardboard
  2.  Get the desired width and height
  3.  Make (construct) the box by
   cutting the cardboard according to width/height
  */
 }
};

Here, we defined a constructor for the Box class. Notice, the name of the constructor function is the same its class name and that it has no return type. Let's complete the definition of our class and use it in code.

#include <iostream>
using namespace std;

class Box {
 int box_width;
 int box_height;

public:
 // Box is the name of the constructor function
 // ITS NAME IS ALWAYS THE SAME AS ITS CLASS NAME
 // Since, a constructor function does not return anything,
 // it does not have a return type before its name
 Box(int width, int height) {
  // this constructor takes width and height

  /*
  Possible steps to make a Box object

  1.  Get a cardboard
  2.  Get the desired width and height
  3.  Make (construct) the box by
   cutting the cardboard according to width/height
  */

  box_width = width;
  box_height = height;

  cout << "Making a new box..." << endl;
  cout << "Gathering some cardboard..." << endl;
  cout << "Width: " << box_width << endl << "Height: " << box_height << endl;
  cout << "Making the box with the given width and height..." << endl;
  cout << "Done! Enjoy your new box" << endl;
 }
};

int main() {
 // Create a Box object named b
 Box b(30, 20);

 return 0;
}

Now, run this program yourself and enjoy making new boxes!

No comments:

Post a Comment

Power function

In C/C++ (and also other languages), we have the built in power function to raise a number to a given power. What if we need to calculate ...