Below are the conditions in which compiler will generate default constructor
1) If the class has member objects that has default constructor
2) If the base class of the class has default constructor
3) If the class has any virtual functions
4) If the class is derived from virtual base class
Note:
If you explicitly provide a constructor to the class then compiler wont generate default constructor and destructor. Its the programmers responsibility to provide all the necessary constructors and destructors.
This is applicable to the copy constructors as well.
For e.g. :
class Base1 {
public:
Base1(const Base1&);
Base1& operator=(const Base1&);
private:
int m_i;
};
int main () {
Base1 b;
}
This will throw compiler error:
test3.cpp:19: error: base `Base1' with only non-default constructor in class without a constructor
test3.cpp: In function `int main()':
test3.cpp:38: error: no matching function for call to `Base1::Base1()'
test3.cpp:10: note: candidates are: Base1::Base1(const Base1&)
References:
1) http://www.informit.com/guides/content.aspx?g=cplusplus&seqNum=363
2) Effective C++ by Scott Meyers
No comments:
Post a Comment