Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple Default Constructors

From this stack overflow question the answer contains this quote:

... definition says that all default constructors (in case there are multiple) ...

How can there be multiple default constructors, and why may that be useful or allowed by the standard?

like image 235
Zuodian Hu Avatar asked Mar 26 '20 22:03

Zuodian Hu


People also ask

How many default constructors are there?

Default Constructors in C++ They are primarily useful for providing initial values for variables of the class. The two main types of constructors are default constructors and parameterized constructors.

How many defaults constructors per class are possible?

Only one Two Three Unlimit.

How many default constructors are there in Java?

In such case, Java compiler provides a default constructor by default. There are two types of constructors in Java: no-arg constructor, and parameterized constructor. Note: It is called constructor because it constructs the values at the time of object creation.

Is default constructor mandatory in C++?

The compiler-defined default constructor is required to do certain initialization of class internals. It will not touch the data members or plain old data types (aggregates like an array, structures, etc…). However, the compiler generates code for the default constructor based on the situation.


2 Answers

Default constructors don't have to have no parameters; they just need to be invocable with no arguments.

This condition is fulfilled by any constructor whose arguments all have defaults.

[class.dtor/1]: A default constructor for a class X is a constructor of class X for which each parameter that is not a function parameter pack has a default argument (including the case of a constructor with no parameters). [..]

struct Foo
{
   Foo(int a = 0);
   Foo(std::string str = "");
};

Now, of course, in this example you cannot actually instantiate a Foo using either of them without providing an argument (the call would be ambiguous). But Foo is still usable, and these are still "default constructors". That's just how the standard has decided to categorise things, for the purpose of defining rules. It doesn't really affect your code or programming.

(By the way, I didn't want to distract but you should have explicit on both of those!)

like image 185
Asteroids With Wings Avatar answered Nov 04 '22 23:11

Asteroids With Wings


Here's an example of a class with two default constructors that can be default constructed:

struct Foo
{
    Foo(); // #1

    template <class... Args>
    Foo(Args...); // #2
};

auto test()
{
    Foo f{}; // ok calls #1
}
like image 44
bolov Avatar answered Nov 04 '22 23:11

bolov