2
votes

I am making a three-dimensional vector class (called Vector3) in c++. Right now, I am trying to overload the stream insertion operator (<<) so that I can directly print all of the vector's components all at once. I copied the sintax from MSD, but I get an 3 errors.

error: passing 'const Vector3 ' as 'this' argument of 'float Vector3::getX()' discards qualifiers [-fpermissive]
error: passing 'const Vector3 ' as 'this' argument of 'float Vector3::getY()' discards qualifiers [-fpermissive]
error: passing 'const Vector3 ' as 'this' argument of 'float Vector3::getZ()' discards qualifiers [-fpermissive]

(differences are marked in bold)

In Vector3.h under public, I entered this function declaration:

friend ostream& operator<<(ostream &os, const Vector3 &vector);

In Vector3.cpp, I implemented it:

ostream& operator<<(ostream& os, const Vector3& vector)
{
    os << "(" << vector.getX() << ", " << vector.getY() << ", " << vector.getZ() << ")" << endl;
    return os;
}

It should print out something like (x, y, z) according to the x, y, and z variables.

On a side note, shouldn't the vector.getX() lines use the -> instead of the dot, because the vector object is an address pointer?

3
Is getX() a const member function? - hmjd
Your operator<< doesn't need to be a friend if it only calls public member functions of Vector3. - Blastfurnace
As to your side note, no it should not - the vector parameter is not a pointer (syntactically), it is a reference. Reference variables have the same "dot" syntax as value variables. - Rob I

3 Answers

7
votes

Add const qualifiers to your get... functions.

class Vector3
{
    public:
        float getX() const {return x;};
};

A const-qualified function simply means you can call it on a const instance of the class. Here, the getters won't change anything. However, if you don't specify that, the compiler doesn't know, so calling a function that might change something on a const variable is not allowed.

You can read about const-correctness here.

And the dot notation is correct, vector is not a pointer, but a reference (i.e. another name for some other Vector3. The & notation can be a little confusing for beginners I think. Roughly: when you apply it to a variable, it takes its address, when it's part of a type, it means that type is a reference. E.g. see here or here.

2
votes

I suspect you've not declared your getX, getY, and getZ functions as const. The compiler won't let you use them because it can't be sure that they do not change the state of the object.

You should be able to change their declarations to the following form:

float Vector3::getX() const
1
votes
float Vector3::getX()

must be changed to

float Vector3::getX() const