Sunday, April 14, 2013

Default Constructors

Default constructors are constructors that doesn't accept any arguments. User can provide the default constructor, if user doesn't provide the default constructor compiler can automatically generate one based on the program needs if the class doesn't contain any const and reference members

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