Nov 13, 2019 at 12:24pm UTC
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)
Nov 13, 2019 at 12:31pm UTC
The xval, yval, zval are global variables.
The class methods should make use of the members x, y, z of point.
Nov 13, 2019 at 1:06pm UTC
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 Nov 13, 2019 at 1:17pm UTC