We need constructor overloading for running different instances of constructors based upon the number of formal arguments in the constructor. But I want to use one single version of constructor, and that should handle multiple cases of object call based on the number of actual arguments passed. For it, can we make constructors with default arguments in C++ ?
Asked
Active
Viewed 94 times
-3
-
If you know the number of arguments at compile time then use a [variadic template](https://en.cppreference.com/w/cpp/language/parameter_pack) constructor. If all the arguments are of the same type, you may consider a vector of said arguments. I usually don't use default arguments just overloads (to avoid those with default arguments to be used in type deduction scenarios) – Pepijn Kramer Aug 21 '22 at 04:18
-
This is explained in any begginer level [C++ book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). See [Writing variadic template constructor](https://stackoverflow.com/questions/28866559/writing-variadic-template-constructor) – Jason Aug 21 '22 at 04:30
1 Answers
-1
Yes, you can define default arguments
I will give an example
class Test {
public:
Test(int x = 0, int y = 10) {
}
};
Cheers, Daniel

HurdOfDaniel
- 30
- 4