I was going through the following Example in my book:
1 2 3 4 5 6 7 8 9 10
class X{};
X f() {return X();}
void g1(X&) {}
void g2(const X&) {}
int main()
{
// g1(f()); Error:Invalid initialiazation of non-const reference of type 'X&' from a temporary of type 'X'
g2(f());
}
I thought that the compiler Would give me an error as there is no constructor X() declared or defined.
But there were no errors.Can someone please explain this to me.
If no constructor is declared for a class then the compiler declares the default constructor implicitly. If it is used in the code then the compiler also defines this default constructor.
For your class the compiler implicitly declares the following functions:
default constructor, copy constructor, move constructor, destructor, copy assignment operator, move assignment operator
From the c++ Standard
12 Special member functions
1 The default constructor (12.1), copy constructor and copy assignment operator (12.8), move constructor and move assignment operator (12.8), and destructor (12.4) are special member functions. [ Note: The implementation will implicitly declare these member functions for some class types when the program does not explicitly declare them. The implementation will implicitly define them if they are odr-used (3.2). See 12.1, 12.4 and 12.8. —end note ] Programs shall not define implicitly-declared special member functions.