I'm just testing a code shown below (learning oop
in c++
).
(system: linux, gcc compiler with -std=c++11
)
#include <iostream>
class Point {
private:
double x, y;
public:
static unsigned int pCount;
// constructor1 with no initial arguments
Point() {
x = 0.0f;
y = 0.0f;
std::cout << "Point()" << " x = " << x << " y = " << y
<< " point no: " << ++pCount << std::endl;
}
/*
// constructor1 alternative: calling another constructor
Point() {
Point(0.0f, 0.0f);
std::cout << "Point()" << std::endl;
}
*/
// constructor2 with initial arguments
Point(double cx, double cy) {
x = cx;
y = cy;
std::cout << "Point(double, double)" << " x = " << x << " y = " << y
<< " point no: " << ++pCount << std::endl;
}
void Show() {
std::cout << "Show()" << " x = " << x << " y = " << y << std::endl;
}
virtual ~Point() {
std::cout << "~Point()" << " x = " << x << " y = " << y
<< " point no: " << pCount-- << std::endl;
}
};
unsigned int Point::pCount = 0;
int main(int argc, char *argv[]) {
Point p1(2.5, 7.6);
Point p2;
p2.Show();
p1.Show();
return (0);
}
The code above creates the output as:
Point(double, double) x = 2.5 y = 7.6 point no: 1
Point() x = 0 y = 0 point no: 2
Show() x = 0 y = 0
Show() x = 2.5 y = 7.6
~Point() x = 0 y = 0 point no: 2
~Point() x = 2.5 y = 7.6 point no: 1
However, when I comment-out the constructor1
and uncomment constructor1 alternative
, the output created gets a little weird as below:
Point(double, double) x = 2.5 y = 7.6 point no: 1
Point(double, double) x = 0 y = 0 point no: 2
~Point() x = 0 y = 0 point no: 2
Point()
Show() x = 4.64944e-310 y = 9.88131e-324
Show() x = 2.5 y = 7.6
~Point() x = 4.64944e-310 y = 9.88131e-324 point no: 1
~Point() x = 2.5 y = 7.6 point no: 0
I think in the latter case (constructor1 alternative
), a temporary object is created and then its pointer is passed to p2
. Anyway, so far, so good... But I'm stuck with the values assigned to the variables x
& y
: The former shows x = 0, y = 0
as expected; however the latter spits out x = 4.63813e-310, y = 9.88131e-324
, though values are very close to zero, it still seems weird to me.
Why the latter case does not assign the exact "zero" values?