c++ - Should T() initialize member variables to zero? -
i new c++, have written sample code:
#include <iostream> class point { public: int x, y; int dis() { std::cout << x << y << std::endl; homecoming x; } int operator=(const point&) { int dat = 3; homecoming dat; } }; int _tmain(int argc, _tchar* argv[]) { point p2 = point(); p2.dis(); homecoming 0; } here p2 should initialize both class point variables x , y 0 right? instead when p2.dis(), getting x , y intialized random values.
and in next case tsum = 0, if "t" of type class.
template<typename t> double getaverage(t tarray[], int nelements) { t tsum = t(); // tsum = 0 (int nindex = 0; nindex < nelements; ++nindex) { tsum += tarray[nindex]; } // whatever type of t is, convert double homecoming double(tsum) / nelements; } how different ?
thanks in advance clarification.
the rules of language requires
point p2 = point(); to value-initialize p2. since point doesn't have user-defined constructor, value-initialization includes zero-initialization , both p2.x , p2.y should zero.
you seeing visual c++ bug (-858993460 0xcccccccc, vc++ fills uninitialized variables in debug mode). workaround provide default constructor point explicitly initializes both fellow member variables zero.
c++ visual-c++ initialization
No comments:
Post a Comment