Reputation: 508
How to initialize parameterised constructor as default constructor in c++? This question was asked in my exam. We were given a parametrized constructor & it worked as default constructor too.
Upvotes: 1
Views: 380
Reputation: 1123
When a constructor can be invoked with no arguments, it is called a default constructor.
However, a constructor that takes arguments can be turned into a default constructor when its arguments are given default values.
For example:
class String {
public:
String(const char∗ p = ""); // default constructor : empty string
// ...
}
Upvotes: 0
Reputation: 29976
A default constructor, per standard (12.1/4), is:
A default constructor for a class X is a constructor of class X that can be called without an argument
So you just need to give the arguments default values:
class Foo
{
public:
Foo(int a = 6)
{
}
};
int main()
{
Foo obj;
}
Upvotes: 5
Reputation: 2723
class A
{
A(int a = 0)
{
std::cout << a;
}
};
Just predefine the parameters with default values.
Upvotes: 1