By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
428,604 Members | 858 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 428,604 IT Pros & Developers. It's quick & easy.

Is any constructor necessary in C++?

P: n/a
Is constructor necessary in C++?
Oct 28 '10 #1
Share this Question
Share on Google+
3 Replies


P: 14
Not necessarily. It depends on your application.

If you don't write a constructor, the compiler supplies a default constructor which creates your object but doesn't do anything else.

If you want the member variables to be initialized, or if you want anything else done when the new object is created, then you have to write a constructor (or several constructors, depending on your requirements).
Oct 28 '10 #2

weaknessforcats
Expert Mod 5K+
P: 9,197
If you don't write a constructor, the compiler supplies a default constructor which creates your object but doesn't do anything else.
Actually, the compiler's default constructor calls the default constructors on each of the class data members.

Creating the object is independent from calling constructors.

If someone else designs a class with an object of your class as a member and then creates a object of their class using the compiler's default constructor, then your class must have a default constructor or their code won't compile.
Oct 28 '10 #3

P: 14
... then your class must have a default constructor ...
... meaning either you don't write any constructor (e.g. you use the compiler-supplied default constructor) OR you write your own default constructor.

In that sense, "default constructor" simply means a constructor that takes no arguments. It may initialize data members or perform other functions.
Oct 28 '10 #4

Post your reply

Sign in to post your reply or Sign up for a free account.