I am trying to create my first class in c++. I am making file called geometryitems.cpp
and doing this:
using namespace std;
class Point
{
double x, y, z;
public:
// constructor
Point(double x, double y, double z)
{
}
// copy constructor
Point(const Point& pnt)
{
x = pnt.x;
y = pnt.y;
z = pnt.z;
}
void display()
{
cout << "Point(" << x << ", " << y << ", " << z << ")";
}
};
Then I call it from another file like this:
#include <iostream>
#include <cstdio>
#include "geometryitems.cpp"
using namespace std;
int main()
{
// initialise object Point
Point pnt = Point(0, 0, 0);
cout << "Point initialisation:" << endl;
pnt.display();
double t = 0;
cout << endl << t << endl;
Point pnt2 = pnt;
pnt2.display();
// keep the terminal open
getchar();
return 0;
}
Here is the output:
t
is shown as normal 0 but other zeros are some other numbers. I would understand if they were just very-very small numbers but there are also very-very big ones...
Why are the zeros in Point
shown as such strange numbers? Is there a way to make it looking as normal zeros?
You are not setting the member variables to any value in your constructor:
Point(double x, double y, double z)
{
}
You need
Point(double x, double y, double z) : x(x), y(y), z(z) {}
This initializes your data members x
, y
, and z
using the constructor initialization list.
You should also remove your copy constructor. The compiler-synthesized one will do just fine.