Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What do explicitly-defaulted constructors do?

Consider the following:

template <class T>
struct myclass
{
    using value_type = T;
    constexpr myclass() = default;
    constexpr myclass(const myclass& other) = default;
    constexpr myclass(const myclass&& other) = default;
    T value;
};
  • To what constructor bodies these function are equivalent?
  • Does myclass<int> x; initialize the integer at 0?
  • For myclass<std::vector<int>> x; what does the default move constructor do? Does it call the move constructor of the vector?
like image 704
Vincent Avatar asked Nov 30 '15 20:11

Vincent


People also ask

What is the purpose of a default constructor?

The default constructor in Java initializes the data members of the class to their default values such as 0 for int, 0.0 for double etc. This constructor is implemented by default by the Java compiler if there is no explicit constructor implemented by the user for the class.

Can we call a default constructor explicitly?

Yes, it is possible to call special member functions explicitly by the programmer.

What happens if you dont define default constructor in C++?

Assuming you're talking about C++ (anyway, this should be similar in most other languages), if you don't call a constructor of the base class explicitly, its default constructor will be called automatically (if one exists; if not, the compiler would fire an error).

Are default constructors necessary?

What is the default constructor? Java doesn't require a constructor when we create a class. However, it's important to know what happens under the hood when no constructors are explicitly defined. The compiler automatically provides a public no-argument constructor for any class without constructors.


1 Answers

They aren't equivalent to any function bodies. There are small but significant differences between the three cases: = default, allowing implicit generation, and the nearest equivalent function body.

The following links explain in more detail:

  • Defaulted default constructor and destructor
  • Defaulted move constructor

I couldn't find a good link about copy-constructor; however similar considerations as mentioned in the other two links will apply.


myclass<int> x; does not set value to 0.

The defaulted move-constructor (if you made it a non-const reference) moves each movable member (although I think there is a special case where if there is a non-movable base class, weird things happen...)

like image 145
M.M Avatar answered Sep 29 '22 01:09

M.M