Why do we need compiler defined constructor?
The compiler defined constructor is empty and does not initialize the member variables. Then why does the compile开发者_Go百科r create one?
Also what is the difference if any between a compiler defined constructor and an user defined empty constructor?
The presence or absence of a constructor affects how users of the class can instantiate the object. If the compiler didn't create a default constructor, then you wouldn't be able to use a class or struct unless you created your own constructor.
The compiler-defined ctor should initialize member variables using the default ctors for the types of those variables. Only POD members remain uninitialized. Also note that when/if you use inheritance, the ctor works in conjunction with base class ctors to create the object.
When you define a ctor yourself, that stops the compiler for generating other ctors for you. For example, if you have something like:
struct X {
int a;
public:
X(int) {}
};
int main() {
X x; // error: no default ctor defined
X x = X(3); // no problem.
}
The fact that you've defined a ctor that takes an int argument means the compiler will not generate a default ctor for you, so the X x;
won't work -- you need to either specify an int argument (that will be ignored) or else define a default ctor for the class. If you comment out the ctor that's defined above, then the compiler will generate a default ctor, so the X x;
would work.
Java-specific
If you don't define a constructor for a class, a default parameterless constructor is automatically created by the compiler. The default constructor calls the default parent constructor (super()) and initializes all instance variables to default value (zero for numeric types, null for object references, and false for booleans).
If you define any constructor for your class, no default constructor is automatically created.
So you don't have to write an empty constructor when you don't need to use one.
A compiler defined constructor is always public and non-explicit. You can customize your empty constructor by making it explicit or private if you want.
Not all compilers will create a default constructor that zero-initializes the data members. I currently am using a couple that do not zero-initialize the data members with defualt constructors.
It just so happens that both major compilers on most major systems will do the initialization (VS 2010, gcc on Windows, Linux, Free BSD, Solaris)
The behavior is the same. The only reason to explicitly create a default constructor is when you also need to create some other constructor in addition to the default constructor that would normally be created by the compiler. The compiler will not create a default constructor if you create a constructor explicitly, whether or not that constructor is a default constructor.
精彩评论