1

I am having issues displaying coordinates that are read into a class. This is my first time using classes so please be understanding! Here is what I have so far:

#include <iostream>

using namespace std;

class Vector{
private:
float x;
float y;
public:
Vector(float f1, float f2)
{
    x=f1;
    y=f2;   
}

Vector(){}

float display()
{
    Vector v;
    cout << "(" << v.x << "," << v.y << ")" << endl;
    return 0;
}


};

 int main()
{
  Vector v1(0.5, 0.5); 

   cout << "v1 ";
   v1.display();
   system("pause");
   return 0;
}

It prints

v1 (-1.07374e+008,-1.07374e+008)
NathanOliver
  • 171,901
  • 28
  • 288
  • 402
Surge
  • 17
  • 1
  • 7

2 Answers2

4

Your problem is that you are not printing out the coordinates of the Vector you created in main() but a default created one in your function. Instead of

float display()
{
    Vector v;
    cout << "(" << v.x << "," << v.y << ")" << endl;
    return 0;
}

You need

float display()
{
    //Vector v; remove this
    cout << "(" << x << "," << y << ")" << endl;
    //           no v.x       no v.y
    return 0;
}

I suggest you change the default constructor to

Vector() : x(0), y(0) {}

So it would have printed

v1 (0,0)

You should also change

Vector(float f1, float f2)
{
    x=f1;
    y=f2;   
}

To

Vector(float f1, float f2) : x(f1), y(f2) {}

As it is a good habit to get into. This can save resources and CPU cycles when dealing with non POD types. For more information see Why should I prefer to use member initialization list?

Community
  • 1
  • 1
NathanOliver
  • 171,901
  • 28
  • 288
  • 402
1

the Vector v; line is a mistake. You are basically creating a new uninitialized vector instead of crating your own instance.

one correction would be:

int display()
{
    cout << "(" << x << "," << y << ")" << endl;
    return 0;
}

since x and y are member of this class

88877
  • 485
  • 3
  • 11
  • Thank you, this really helps and is working now. I have another issue with it though. I want to initialise a coordinate set to (0,0) if its undeclared. For example, if I add: Vector v2(); v2.display(); it doesn't currently output (0,0), instead something similar to the exponential value in OP. – Surge Jan 06 '16 at 14:47
  • @Surge: two simple choice for it: use default value (not recommended) or create a new constructor with no input parameters `Vector(){x=0.0; y=0.0;}` – 88877 Jan 06 '16 at 14:51