Class object overwritten

Greetings

I have an issue where I've made a simple point class. When i instantiate two different objects of the same class, somehow, the first instance is overwritten by the values of the second. Can anyone help me rectify this issue? Cheers!

//----------------------------------------------------------------------------
point.h

class point
{
private:
double x, y, z;
public:
point(double = 0.0, double = 0.0, double = 0.0); //Constructor
void print(); //Print point
};

//----------------------------------------------------------------------------
point.cpp
#include <iostream>
#include "point.h"

using namespace std;

double xval;
double yval;
double zval;

point::point(double x, double y, double z) //Constructor
{
xval = x;
yval = y;
zval = z;
}

void point::print() //Print point
{
cout << "(" << xval << "," << yval << "," << zval << ")" << endl;
}

//----------------------------------------------------------------------------

int main()
{
point p1(1, 1, 1);
point p2(2, 2, 2);
p1.print();
p2.print();
}

//----------------------------------------------------------------------------
output:
(2,2,2) // <--- Why is this not (1,1,1) ?
(2,2,2)
The xval, yval, zval are global variables.

The class methods should make use of the members x, y, z of point.
Thank you for the fast reply! I changed the code to the following, and it seems to work now:

//point.h -----------------------------------------------------------

#pragma once

class point
{
private:
double xval, yval, zval;
public:
point(double = 0.0, double = 0.0, double = 0.0); //Constructor

void print(); //Print point

//point.cpp -----------------------------------------------------------

#include <iostream>
#include "point.h"

using namespace std;

point::point(double x, double y, double z) //Constructor
{
xval = x;
yval = y;
zval = z;
}

void point::print() //Print point
{
cout << "(" << xval << "," << yval << "," << zval << ")" << endl;
}

//main.cpp -----------------------------------------------------------

point p1(1, 1, 1);
point p2(2, 2, 2);
p1.print();
p2.print();

//Output -----------------------------------------------------------
(1,1,1)
(2,2,2)


Cheers =]
Last edited on
Good.

Note: Your constructor assigns values after initialization.
Member initialization list syntax avoids assignment.
1
2
3
4
5
6
point::point( double x, double y, double z )
 : xval{ x },
   yval{ y },
   zval{ z }
{
}

Base classes and const members (when you get to them) require that you know the latter syntax.
Topic archived. No new replies allowed.