Inside of a header file (Point.h), I've created a class template. I need to override the addition operator as shown below, so what I have done is declared it as a friend. However, when I try to access the private member variable std::vector<T>coord from within the body of the overloaded function, the compiler complains with the following error:

'std::vector<double, std::allocator<double> > Point<double>::coord' is private

Must I make the member variable std::vector<T>coord public, or can I keep it private with a small modification of my code? Here is a snippet from the Point.h file demonstrating the issue.

template <class T>
class Point
   template <class U>
   friend const Point<U> operator+(const U &lhs, const Point<U> &rhs);
std::vector<T> coord;

template <class T> Point<T>::Point()
{   }

template <class U> const Point<U> operator+(const U &lhs, Point<U> &rhs)
   rhs.coord[0] = 1;  // ERROR occurs here
return rhs;

Edited by nkinar: Made slight modification to code

8 Years
Discussion Span
Last Post by nkinar

Oh no--my mistake! All that is required is indeed a small change. This line must be modified:

friend const Point<U> operator+(const U &lhs, const Point<U> &rhs);

Here is the modification:

friend const Point<U> operator+(const U &lhs, Point<U> &rhs);

It's one of these things where you have seen the code again and again, and can't see the forest for the rest of the trees.

Edited by nkinar: Clarification

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.