logo of SA Coder
        Menu
sign in

      References



Understanding Parameterized Constructors in C++



In C++, constructors are special functions that are automatically called when an object of a class is created. Constructors are used to initialize the variables of an object and ensure that the object is in a valid state before it can be used. One type of constructor is the parameterized constructor, which allows you to pass arguments to the constructor when an object is created.



A parameterized constructor is created by adding parameters to the constructor function, just like any other function. The parameters are used to initialize the object when it is created. Here is an example of a simple class that includes a parameterized constructor


copy

#include <iostream>
using namespace std;

class MyClass {
    int a, b;
  public:
    MyClass(int i, int j) {a=i; b=j;}
    void show() {cout << a << " " << b;}
};

int main() {
  MyClass ob(3, 5);
  ob.show();
  return 0;
}



In this example, the constructor 'MyClass(int i, int j)' takes two parameters, 'i' and 'j', which are used to initialize the variables 'a' and 'b'. The 'show()' function is used to display the values of 'a' and 'b' on the console.



Parameterized constructors are very useful because they allow you to initialize objects efficiently without having to make additional function calls. This makes your program more efficient and easier to read.



You can also create a constructor with only one parameter. In this case, there is a special syntax that can be used to initialize the object. For example:


copy

class MyClass {
    int x;
  public:
    MyClass(int i) : x(i) {}
    void show() { cout << x; }
};

int main() {
  MyClass ob(3);
  ob.show();
  return 0;
}



In this example, the constructor 'MyClass(int i)' takes one parameter, 'i', which is used to initialize the variable 'x' using a special syntax : 'x(i)'. The 'show()' function is used to display the value of 'x' on the console.


Summary



parameterized constructors in C++ are an efficient way to initialize objects and ensure that they are in a valid state before they can be used. By passing arguments to constructors, you can avoid making additional function calls and make your program more efficient.



Please login first to comment.