Bjarne wrote:-
For a type T, T() is the notation for the default value , as defined by the default constructor .
What happen when we don’t declare default constructor ? For example
using namespace std;
class date{
int n,m;
public:
int day(){return n;}
int month(){return m;}
};//no default constructor
int main()
{
date any =date();
cout<<any.month()<<endl;
cout<<any.day()<<endl;
return 0;
}
Output of this program is 0 and 0 every time i run my program. I haven’t declare any default constructor then why there exits a default value i.e. 0?
EDIT-
class date{
int n,m;
public:
date (){
m=1;}
int day(){return n;}
int month(){return m;}
};
int main()
{
date any =date();
cout<<any.month()<<endl;
cout<<any.day()<<endl;
return 0;
}
After reading answers i provide a default constructor but now n is getting garbage value but according to answers it should be 0 as m is out of reach of any other constructor and it is value initialisation as mentioned in answer
The behavior you see is Well-Defined for your class.
How & Why is the behavior Well-Defined?
The rule is:
If you do not provide a no argument constructor the compiler generates one for your program in case your program needs one.
Caveat:
The compiler does not generate the no argument constructor if your program defines any constructor for the class.
As per the C++ Standard an object can be initialized in 3 ways:
When, a type name or constructor initializer is followed by
()the initialization is through value initialization.Thus,
Value Initializes an nameless object and then copies it in to the local object
any,while:
would be a Default Initialization.
Value Initialization gives an initial value of zero to members that are out of reach of any constructor.
In your program,
nandmare beyond the reach of any constructor and hence get initialized to0.Answer to Edited Question:
In your edited case, your class provides a no argument constructor,
date(), which is capable(& should) initialize membersnandm, but this constructor doesn’t initialize both the members, So In this case no zero initialization takes place, and the uninitialized members in the object have an Indeterminate(any random) value, further this temporary object is copied toanyobject which displays the shows indeterminate member values.For Standerdese Fans:
The rules for object Initialization are aptly defined in:
C++03 Standard 8.5/5: