If we say that the default constructor
is that constructor without parameters, can we also say the the constructor created by the compiler is also a defau
The default constructor is a constructor that may be called without arguments. So this is either a constructor that has no arguments, or a constructor whose arguments all have default values.
But yes, the compiler generates a default constructor if you don't provide any other constructors.
Recommended reading: http://www.parashift.com/c++-faq-lite/ctors.html#faq-10.4.
A default constructor is one that can be called without arguments.
C++98 §12.1/5:
A default constructor for a class
X
is a constructor ofX
that can be called without an argument. If there is no user-declared constructor for classX
, a default constructor is implicitly declared.
+------> Implicitly GENERATED by compiler
|
|
Default Constructor -----+
|
|
+------> Explicitly provided by programmer
Basically, a default ctor is a ctor with no-args.
PLEASE note that the compiler will not generate any default ctor in following case:
class WontGenerateDefCtoByCompiler
{
private:
char* iHaHaPtr;
};
Reason being the compiler does not see any need to initialize programmer provided pointer. It is programmer's responsbility to correctly write and init the default ctor.
If you, on other hand, write a virtual function inside the above class, compiler will definitely generate a default ctor (but won't initialise iHahaptr pointer for you). Further, such ctor will be generated ONLY IF an instance of that object was created in the program (otherwise, again, no ctor will be generated by compiler).
These are the ONLY 4 conditions in which compiler will IMPLICITLY generate default ctor (if not provided by programmer):
(1) The class has a virtual function (Why? need to setup vptr correctly )
(2) The class is derived from another class that has default ctor (either implicitly generated or explictly provided)
(3) The class has a member that has default ctor (either implicitly generated or explictly provided)
(4) The class is virtually derived from other class
In all other cases, compiler will not generate any default ctor.
You can't just say that "the constructor created by the compiler is also a default constructor". If there are no constructors declared, the compiler generates a default constructor and a copy constructor (and possibly a move constructor if we are talking C++0x here). When you mention just "the constructor created by the compiler", you are actually talking about at least two constructors at once. So you can only say that "the default constructor created by the compiler is also a default constructor", but this sounds like something Capt. Obvious would say.