My Question is when we create a object of any class in c++ then if we have not provided any type of constructor in our class then c++ compiler provides its own default constructor. So why compiler provides its own constructor. Thanks in Advance.
1 Answer
I have not looked up any history on the matter, but here are some possible reasons:
If a default constructor was not implicitly defined, then the following would not compile:
struct X { std::string str; }; //... X x; because X would not have a default constructor. You would instead need to write
struct X { std::string str; X() : str() {} }; //... X x; which seems unnecessary cumbersome, when it is clear what was intended. And in contrast to initialization with arguments, this is a common use case with clear semantics.
Also, as long as the class is plain old data (POD), meaning that it is a class that would also be allowed as a C structure, then it was (and is) intended that C++ be (mostly) compatible with C. In C for example
struct X { int i; }; //... struct X x; is allowed and so it should also be allowed in C++. If there wasn't a default constructor that default-initializes each member, then there would need to be special rules for such class and initialization to not need to call a constructor and just leave the members with indeterminate values. But the same rule should not be applied to class members which do have proper constructors, since it shouldn't be possible to leave a class type with class invariants in an indeterminate state.
private, implement a different default constructor, or otherwise use= deletein C++11 or newer.struct C { std::string s; C() : s() {} };