Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
What is Parameterized Constructor?
2.
How Parameterized Constructor Works in C++?
3.
Examples of Parameterized Constructor
3.1.
Example 1
3.2.
C++
3.2.1.
Output
3.2.2.
Explanation
3.3.
Example 2 
3.4.
C++
3.4.1.
Output
3.4.2.
Explanation
3.5.
Example 3
3.6.
C++
3.6.1.
Output
3.6.2.
Explanation
3.7.
Example 4
3.8.
C++
3.8.1.
Output
3.8.2.
Explanation
4.
Difference between Default and Parametrized Constructor
5.
Frequently Asked Questions
5.1.
What is parameterized constructor in C++?
5.2.
What is parameterized constructor advantage?
6.
Conclusion
Last Updated: Jun 10, 2024
Easy

Parameterized Constructors in C++

Author Kanak Rana
0 upvote

Parameterized constructors in C++ are constructors that accept parameters. They enable programmers to create objects with specific properties and attributes by passing arguments. Multiple parameterized constructors can be defined in a class, offering flexibility in object initialization. Unlike Java, the compiler in C++ doesn't create a default constructor when a programmer defines their own constructor.

Parameterized Constructors in C++

In C++, when we create an object using a parameterized constructor, we provide it with specific information or values. The constructor then uses this information to initialize the object with the desired features or configurations. It allows us to create objects tailored to our requirements by passing relevant parameters.

What is Parameterized Constructor?

Parameterized constructors in C++ are constructors that accept parameters. They enable programmers to create objects with specific properties and attributes by passing arguments. Multiple parameterized constructors can be defined in a class, offering flexibility in object initialization. Unlike Java, the compiler in C++ doesn't create a default constructor when a programmer defines their own constructor.

How Parameterized Constructor Works in C++?

In C++, a parameterized constructor is a special type of constructor that takes parameters during the creation of an object. Here's how it works:

1. Declaration: You declare a parameterized constructor within a class, specifying parameters that it will accept. For example:

class MyClass {
public:
   // Parameterized constructor declaration
   MyClass(int param1, double param2);
};

 

2. Definition: In the class implementation, you define the parameterized constructor, initializing the object's attributes with the provided parameters. For instance:

// Parameterized constructor definition
MyClass::MyClass(int param1, double param2) {
   // Initialize object attributes with parameters
   // ...
}

 

3. Object Creation: When you create an object of the class, you provide values for the parameters:

int main() {
   // Create an object with specific values
   MyClass obj(42, 3.14);
   // ...
}

 

4. Initialization: The parameterized constructor is called automatically during object creation, initializing the object's attributes with the provided values. In the example, obj is created with param1 set to 42 and param2 set to 3.14.

Examples of Parameterized Constructor

Example 1

  • C++

C++

#include <iostream>
#include <string>

using namespace std;

// Create a class.
class Birdhouse {
private:
int numHoles;
string color;

public:
// Parameterized constructor
Birdhouse(int numHoles, string color) {
this->numHoles = numHoles;
this->color = color;
}

void displayInfo() {
cout << "Number of holes: " << numHoles << endl;
cout << "Color: " << color << endl;
}
};

// Main function
int main() {
int numHoles;
string color;

cout << "Enter number of holes: ";
cin >> numHoles;

// Ignore the newline character in the input buffer
cin.ignore();
cout << "Enter color: ";
getline(cin, color);

Birdhouse myBirdhouse(numHoles, color);
myBirdhouse.displayInfo();

return 0;
}
You can also try this code with Online C++ Compiler
Run Code


Output

Enter number of holes: 2
Enter color: Red
Number of holes: 2
Color: Red

 

Explanation

The code defines a `Birdhouse` class in C++ with a parameterized constructor that takes the number of holes and color as arguments. It also includes a `displayInfo()` method to show the birdhouse's details. In the `main()` function, user input for the number of holes and color is taken and used to create a `Birdhouse` object. The `displayInfo()` method is then called to display the birdhouse's information.

explanation

Example 2 

  • C++

C++

#include <iostream>

class ExamResult {
private:
int eng, science, maths, obtained;
int max = 300;
float result;

public:
ExamResult(int a, int b, int c) {
maths = a;
eng = b;
science = c;
obtained = eng + science + maths;

// Perform division using float.
result = (static_cast<float>(obtained) / max) * 100;
std::cout << result;
}
};

int main() {
ExamResult x1(90, 80, 99);
return 0;
}
You can also try this code with Online C++ Compiler
Run Code

Output

89.6667

 

Explanation

The code defines a class ExamResult to represent an exam result. It has private variables for scores and the result. The constructor takes scores as parameters, calculates the total obtained marks and the result using floating-point division, and prints the result. In main(), an ExamResult object is created with scores 90, 80, and 99, displaying the calculated result.

Example 3

  • C++

C++

#include<iostream>

class Point {
private:
int x;
int y;

public:
// Parameterized constructor
Point(int xCoord, int yCoord) : x(xCoord), y(yCoord) {}

// Display the coordinates
void display() {
std::cout << "Point coordinates: (" << x << ", " << y << ")\n";
}
};

int main() {
// Create a Point object with specific coordinates
Point point1(3, 7);

// Display the coordinates using the member function
point1.display();

return 0;
}
You can also try this code with Online C++ Compiler
Run Code

Output

Point coordinates: (3, 7)

 

Explanation

In this example, the Point class represents a point in a 2D space with x and y coordinates. The class has a parameterized constructor that initializes the x and y attributes with the provided values during object creation. In the main function, a Point object (point1) is created with coordinates (3, 7) using the parameterized constructor. The display member function is called to showcase the coordinates of the created point.

Example 4

  • C++

C++

#include<iostream>
#include<string>

class Employee {
private:
std::string name;
int age;

public:
// Parameterized constructor
Employee(const std::string& empName, int empAge) : name(empName), age(empAge) {}

// Display employee details
void display() {
std::cout << "Employee: " << name << ", Age: " << age << " years\n";
}
};

int main() {
// Create an Employee object with specific details
Employee emp1("John Doe", 30);

// Display employee details using the member function
emp1.display();

return 0;
}
You can also try this code with Online C++ Compiler
Run Code

Output

Employee: John Doe, Age: 30 years

 

Explanation

In this example, the Employee class represents an employee with a name and age. The class has a parameterized constructor that initializes the name and age attributes with the provided values during object creation. In the main function, an Employee object (emp1) is created with the name "John Doe" and age 30 using the parameterized constructor. The display member function is called to showcase the details of the created employee.

Difference between Default and Parametrized Constructor

Default ConstructorParameterized Constructor
Provided by the compiler if no other constructor is defined.Constructor with one or more parameters.
NO parameters.One or more parameters.
The purpose is to initialize instance variables with default values.The purpose of a parameterized constructor is to assign user-wanted specific values to the instance variables of different objects.

Example: public CodingNinjas() {

}

Example: public CodingNInjas(int x, String y) 

{

this.x = x; 

this.y = y; 

}

 

Also see - Difference between argument and parameter

Frequently Asked Questions

What is parameterized constructor in C++?

In C++, a parameterized constructor is a constructor that takes parameters during the creation of an object. Unlike a default constructor, which has no parameters, a parameterized constructor allows you to initialize the object's properties with specific values provided as arguments.

What is parameterized constructor advantage?

The advantage of a parameterized constructor lies in its ability to customize object initialization. By accepting parameters, the constructor enables the creation of objects with specific attributes, providing flexibility and reusability in the code. This customization is particularly useful when different instances of the same class need to be initialized with distinct values.

Conclusion

In this article, we have discussed about the Parametrized Constructors in C++. We have discussed how does it works. We have also considered some examples to understand the concept of parameterized constructor. Then we have explained the differences between default and parameterized constructors for better understanding.

If you want to know more about “Parametrized Constructors in C++” and topics like this. In that case, refer to the following articles:

Refer to our guided paths on Code 360 to learn more about DSA, Competitive Programming, JavaScript, System Design, etc. Enrol in our courses and refer to the mock test and problems available. Take a look at the interview experiences and interview bundle for placement preparations.

Live masterclass