mushisgosu mushisgosu - 12 days ago 5
C++ Question

Multiple dot operator (c++ class)

so here is my task:

I have to create class Vector which sets coordinates of multi-dimensional vector and will work when called with this specific code (cant change this part):

const int NumOfDimensions = 5;
Vector x (NumOfDimensions);
x.Set(0, 1.1).Set(1, 1.2).Set(2, 1.3).Set(3, 1.4).Set(4, 1.5);
x.print();


and the output has to be like this:

(1.1, 1.2, 1.3, 1.4, 1.5)


so this is what I tried but couldnt get it to work (this part has to be changed)

class Vector {
float *coordinates;
int dimensions;

public:
Vector(int k)
{
coordinates = new float[k];
dimensions = k;
}
void Set(int k, float wsp)
{
//Vector x(k+1);
coordinates[k] = wsp;
//return x;
}
void print()
{
int i;
cout<<"(";
for(i=0; i<dimensions; i++)
cout<<coordinates[i]<<", ";
cout<<")"<<endl;
}
};


So I know function Set has to be different and probably return an object but tried lots of different ways and it just doesnt work. Please help me good people of stackoverflow.

Answer

If you want to be able to chain methods of that sort you need to return a reference:

Vector& Set(int k, float wsp) {
  // ...

  return *this;
}

I'd argue that even though you see a lot of that in other languages like Python, Ruby and so on, that interface isn't very C++.

You'd be better off using std::vector to store your coordinates, the C-style arrays are nothing but trouble. This code actually has a severe memory leak since you don't de-allocate with delete[], there's no destructor defined. Using a Standard Library container offloads that responsibility.

Another thing you can do to make this more natively C++ is to define a formatter for it so you can simply dump this to cout directly instead of having a clunky method called print which does it for you:

std::ostream& operator<<(std::ostream& stream, const Vector& vec);

That will permit the use of that formatter on any stream, not just cout.