0

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.

9
  • 1
    So you can construct the object. If you don't want it you can mark it as private, implement a different default constructor, or otherwise use = delete in C++11 or newer. Commented Sep 10, 2022 at 21:04
  • 1
    @orhtej2 That's about the copy constructor, not the default constructor. Commented Sep 10, 2022 at 21:15
  • So it can call default constructors of class members. Otherwise you have to add explicit constructors for simple classes like struct C { std::string s; C() : s() {} }; Commented Sep 10, 2022 at 21:17
  • 1
    Likely C compatibility. A structure object in C can be default initialized without providing an initializer. Without implicit default constructors, the same C code will not be valid to a C++ compiler. C parity (to an extent) was a goal. There is some merit however to requiring c'tors being declared explicitly. But C++ is a product of its time(s). Commented Sep 10, 2022 at 21:18
  • Even if you write default constructor it still will generate code that calls all default constructors of class members, and this will be executed before your logic. So your question is not fully correct Commented Sep 10, 2022 at 21:38

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.