In C++, a parameterized constructor refers to a constructor that has the capability to accept one or more arguments. These specialized constructors serve the purpose of providing values for initializing an object at the time of its creation. By utilizing a parameterized constructor, it becomes feasible to set up an object with multiple values instead of relying on the default initialization process. When defining the constructor's implementation, the parameters can be employed to set the initial values of the object's data members.
Syntax:
It has the following syntax:
class ClassName {
public:
// Parameterized Constructor
ClassName(data_type arg1, data_type arg2, ...) {
// initialization code
}
};
In this syntax,
- ClassName: It represents the name of the class.
- public: It represents the access modifiers of the class.
- data_type: It is used to represent the type of data.
- arg1, arg2, ...: These represent the arguments of the class.
C++ Parameterized Constructor Example
Let's consider a scenario to demonstrate the parameterized constructor in C++.
Example
#include <iostream>
using namespace std;
class Employee {
string name;
int age, salary;
public:
// using Parameterized Constructor
Employee(string n, int a, int s) {
name = n;
age = a;
salary = s;
}
void show() {
cout << "Employee Name: " << name << ", Age: " << age << ", Salary: "<< salary << endl;
}
};
int main() {
Employee emp1("Jhonson", 21, 45000); // calling parameterized constructor
Employee emp2("Michael", 19, 53000);
emp1.show();
emp2.show();
return 0;
}
Output:
Employee Name: Jhonson, Age: 21, Salary: 45000
Employee Name: Michael, Age: 19, Salary: 53000
Explanation:
In this instance, we are examining an Employee class containing attributes such as name, age, and salary. These attributes are set directly through the constructor when creating objects. Following this, two employees, emp1 and emp2, are instantiated with distinct values, and the display method showcases their information.
C++ Parameterized Constructor with Destructor Example
Let's consider a scenario to demonstrate the parameterized constructor along with a destructor in the C++ programming language.
Example
#include <iostream>
using namespace std;
// using parameterized constructor
class ParamCode {
public:
int x;
ParamCode (int i);
~ParamCode ();
};
ParamCode::ParamCode (int i) {
x = i;
}
ParamCode::~ParamCode() {
cout<< "After destructing the objects which are having the value of x is as follows: " << x <<" \n";
}
int main () { //main function
ParamCode t1(20);
ParamCode t2(15);
cout<< "The values for t1.x is: "<<t1.x <<"\n" << "The values for t2.x is: "<<t2.x << "\n";
return 0;
}
Output:
The values for t1.x is: 20
The values for t2.x is: 15
After destructing the objects which are having the value of x is as follows: 15
After destructing the objects which are having the value of x is as follows: 20
Explanation:
In this instance, we are demonstrating a class named ParamCode where the variable x is set through the constructor during the creation of objects t1 and t2 with values 20 and 15 respectively. Subsequently, it exhibits the values of x for both objects. Upon the program's conclusion, the destructor is invoked automatically, showcasing the x values for each object as they are being destroyed.
Default Arguments with Parameterized Constructor in C++
In C++, a parameterized constructor can include a default constructor as well. This feature enables setting default values for the parameters of parameterized constructors. When no arguments are provided during object instantiation, the constructor can automatically apply the predefined default value. This functionality aids in minimizing the need for numerous overloaded constructors, thereby enhancing the simplicity, efficiency, and adaptability of the code.
Syntax:
It has the following syntax:
class ClassName {
public:
ClassName(type1 arg1 = default_value1, type2 arg2 = default_value2) {
// initialization code
}
};
In this syntax,
- ClassName: It represents the name of the class.
- type1 arg1: It represents the argument with its data type.
- default_value: It represents the default value of the argument that is assigned to the parameter.
C++ Default Arguments with Parameterized Constructor
Let's consider a scenario to demonstrate the use of default arguments with a parameterized constructor in C++.
Example
#include <iostream>
using namespace std; //using standard namespace
class CppTutorial {
public:
int val;
// Initialized with the default values
CppTutorial( int p = 2 ) {
val = p;
}
};
int main( ) {
CppTutorial obj1( 7 );
CppTutorial obj2;
cout<< "The resultant output is : " << endl;
cout << obj1.val << endl;
cout << obj2.val;
return 0;
}
Output:
The resultant output is :
7
2
Explanation:
In this illustration, we are examining a class named CppTutorial containing a constructor. The constructor accepts an integer parameter, denoted as p, with a default value of 2 if no argument is supplied. Upon creating obj1 with the value 7, its attribute is initialized to 7. Conversely, obj2 is instantiated without any parameter, causing it to adopt the default value of 2. Subsequently, the program outputs the results to the console.
Member Initializer Lists in Parameterized Constructors
In C++, member initializer lists provide a way to directly initialize class data members before the constructor body is executed. Utilizing the colon (:) during object creation allows for the initialization of values, followed by the initialization list.
Syntax:
It has the following syntax:
class ClassName {
type1 par1;
type2 par2;
public:
ClassName(type1 a, type2 b) : par1(a), par2(b) {
// constructor body (optional)
}
};
C++ Member Initializer Lists in Parameterized Constructors Example
Let's consider a scenario to demonstrate the member initializer lists within a parameterized constructor in the C++ programming language.
Example
#include <iostream>
using namespace std; //using standard namespace
class CppTutorial {
int x, y;
public:
// Parameterized constructor with initializer list
CppTutorial(int a, int b) : x(a), y(b) {}
void show() {
cout << "x = " << x << ", y = " << y << endl;
}
};
int main() {
CppTutorial t1(15, 30);
CppTutorial t2(8, 20);
t1.show();
t2.show();
return 0;
}
Output:
x = 15, y = 30
x = 8, y = 20
Explanation:
In this instance, we are examining the class CppTutorial, containing a pair of private variables, x and y, which receive initial values directly through the initializer list during object instantiation. Subsequently, we create two objects, t1 and t2, with values (15, 30) and (8, 20) respectively. Lastly, the show method displays these assigned values.
Uses of Parameterized Constructor
The parameterized constructor can be used in several scenarios. Some of them are as follows:
- It is very useful to initialize data elements of different objects that contain different values during object creation.
- When we want to overload the constructor, we can make use of a parameterized constructor with different signatures.
- It can be used to avoid separate setter calls after object creation.
Conclusion
In summary, a parameterized constructor in C++ enables the initialization of objects with specific values during their creation, enhancing code flexibility and readability. It eliminates the need for individual setter functions and can accept multiple arguments. The utilization of initializer lists with parameterized constructors enhances efficiency, particularly for const members, references, or initializing base classes. Proficiency in parameterized constructors empowers developers to craft thoroughly initialized and resilient objects within C++ applications.
Parametrized Constructors FAQs
Yes, it is possible to have multiple parameterized constructors in C++.
Yes, it is possible to define multiple parameterized constructors through constructor overloading. To achieve overloading, we can specify a set of unique parameters for each constructor.
In C++, a parameterized constructor is invoked when an object is created and initialized with specific arguments provided in the constructor parameters.
When an object is instantiated with arguments that correspond to its parameter list, it is automatically invoked.
In C++, arguments are passed to a parameterized constructor during object instantiation.
Similarly to how objects are instantiated during function invocations with arguments passed, parameters can be passed to a parameterized constructor in a similar fashion.
4) Are parameterized constructors mandatory in C++?
No, there is no requirement to construct a parameterized constructor when default initialization suffices. Parameterized constructors prove advantageous for setting specific values, enhancing readability, and avoiding the use of uninitialized variables.
5) If we neglect to create any C++ constructors, the compiler will automatically generate a default constructor for us.
In C++, when constructors are not explicitly defined, the compiler generates a default constructor by default. This default constructor initializes the default values for its members. Conversely, if a custom constructor is defined, the compiler will not generate a default constructor.