Parameterized constructor
- C++ course
- Intermediate
- Lesson 8/116
- 5 min
Learn to initialize objects with parameterized constructors.
Parameterized constructor
A constructor can also take parameters. This lets you give an initial value from outside when the object is created. A parameterized constructor is written with a parameter list in parentheses after the class name.
Example: class Score { public: Score(int s) { points = s; } int points; };. Usage: Score score(100);. This line both creates the object and sets points to 100. Once a parameterized constructor is defined, the default constructor is no longer generated automatically; you must write one yourself if needed.
Direct initialization
There are two ways to create an object with a parameterized constructor. The classic way uses parentheses: Score score(100);. Modern C++ also allows braces: Score score{100};. Both call the same constructor.
The brace form has the advantage of rejecting narrowing conversions. Score score{3.5}; gives a compile error if Score(int) is defined, because 3.5 narrows from double to int. The parenthesis form would silently convert and lose data. That is why modern C++ prefers the brace form.
Practice Add a parameterized constructor to the Score class
Define a Score class. Under public: add the constructor Score(int s) { points = s; } and the int points; member variable. In main create an instance with Score score(100); and print points with std::cout.
Starter code
#include <iostream>
// Define the Score class here
int main() {
// Create a Score instance with the parameterized ctor and print points
return 0;
}Sample solution
#include <iostream>
class Score {
public:
Score(int s) {
points = s;
}
int points;
};
int main() {
Score score(100);
std::cout << score.points;
return 0;
}Expected output
100
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the parameterized constructor call
Score score____;
Score score(100);
Explanation: Score score(100); passes the value as a parameter.
2 If only Score(int) is defined in Score, what happens with Score s;?
class Score { public: Score(int s); };- Works, default constructor is called
- Works, s is zeroed
- Gives a compile error Correct answer
- Works, s gets a garbage value
Explanation: With a parameterized constructor, no default constructor is generated.
3 Match each call to its result
| Term | Meaning |
|---|---|
Score s(100); |
100, parentheses |
Score s{100}; |
100, braces |
Score s{3.5}; |
compile error |
Score s; |
default constructor |