Problem with default member functions of class in C++ (constructor, destructor, operator=, copy constructor) (default ctor, dtor, copy ctor)
We know that compiler generates some member functions for user-defined class if that member functions are not defined but used, isn't it. So I have this kind of code:
cl开发者_如何学Goass AA
{
};
void main()
{
AA a;
AA b(a);
a = b;
}
This code works fine. I mean no compiler error. But the following code....
class AA
{
int member1;
int member2;
};
But this code gives an run time error, because variable "a" is used without being iniltialized!!!
So my question is this: when we instantiate an int, it has a value. So why the default constructer doesn't work and by using those two int numbers initializes variable "a"??
EDIT: Platform: Win Vista, Compiler: Visual Studio 2008 compiler; Flags: Default
The compiler-synthesised default constructor calls the default constructors for all class members that have constructors. But integers don't have constructors, and so are not initialised. However, I find it hard to believe that this will cause a run-time error.
To initialise those variables:
class AA {
public:
AA() : member1(0), member2(0) {}
private:
int member1;
int member2;
};
Firstly, from practical point of view this is not a genuine run-time error. This is a built-in debugging feature of your development environment. The compiler attempts to catch situations when your read an uninitialized value, which is exactly what happens in your case.
Secondly, when we "instantiate" an int
, it doesn't have a value. More precisely, it contains an undetermined value which is not even guaranteed to be stable (you can get different values by reading the same uninitialized variable several times in a row). Theoretically, reading an uninitialized int
variable leads to undefined behavior, since it might contain an illegal ("trap") representation. In fact, you can perceive your "run-time error" generated by your development environment as a manifestation of that undefined behavior.
What platform? compiler? compiler flags? You must have some extra checking being added because there is nothing in normal C++ that checks initialization status.
In fact, the default and copy constructors do work. But in cpp uninitialized variables actually contain garbage. Therefore, you get your error (int member1
, int member2
contains trash and you try to assign this trash to b
object).
Firstly, When you instantiate an int without initializing it, it has an indeterminate value. A built-in basic type does not have a constructor.
Secondly, that code should not generate a runtime error. It just copies indeterminate int values in the autogenerated copy constructor and assignment operators. It should generate a compiler warning that an uninitialized variable is being used.
Thirdly, your signature for main is wrong - the correct signature is
int main(void)
精彩评论