Search code examples
c++classscopenon-member-functions

Class scope and private members?


I am defining a function to add elements to the vector<Point> original_points, named
void add_point(). Why is highlighting original_points as undefined, in the function body, when I am using type qualifier: friend (to gain access) and it is in the scope of the class?

// data structure representing Point in 2D plane
class Point{
public:
  //contructors
  Point();
  Point(double x, double y);
  // non-modifying methods
  inline double get_xcoord()const{return xcoord;}
  inline double get_ycoord()const{return ycoord;}
  // modifying methods
  inline double set_xcoord(double x){xcoord=x;}
  inline double set_ycoord(double y){ycoord=y;}
  // non-member function with access to private members
  friend inline void add_point(const Point& p){original_points.push_back();}
private:
  double xcoord;
  double ycoord;
  vector<Point> original_points;};

What am I doing wrong?


Solution

  • The friend is a non-member function, so it can't access non-static members directly; it would need a Point object to act on. You also need to pass something to push_back.

    It's unclear whether the function parameter p should be the object to access, the object to pass to push_back, or both; or whether this should actually be a member, not a friend. The latter seems more likely - you probably want:

    void add_point(const Point& p){original_points.push_back(p);}