Computernerd
Computernerd

Reputation: 7766

How to access the method of a class which is a private member of another class

I have 2 classes , CLASS locationdata is a private member of CLASS PointTwoD .

CLASS locationdata

class locationdata
{
  public:
  locationdata(); //default constructor
  locationdata(string,int,int,float,float); //constructor

 //setter
 void set_sunType(string);
 void set_noOfEarthLikePlanets(int);
 void set_noOfEarthLikeMoons(int);
 void set_aveParticulateDensity(float);
 void set_avePlasmaDensity(float);

 //getter 
 string get_sunType();
 int get_noOfEarthLikePlanets();
 int get_noOfEarthLikeMoons();
 float get_aveParticulateDensity();
 float get_avePlasmaDensity();


 static float computeCivIndex(string,int,int,float,float);
 friend class PointTwoD;

private:

  string sunType;
  int noOfEarthLikePlanets;
  int noOfEarthLikeMoons;
  float aveParticulateDensity;
  float avePlasmaDensity;

};

CLASS PointTwoD

  class PointTwoD
{
  public:
  PointTwoD();
  PointTwoD(int, int ,locationdata);

  void set_x(int);
  int get_x();

  void set_y(int);
  int get_y();

  void set_civIndex(float);
  float get_civIndex();

  locationdata get_locationdata();



  bool operator<(const PointTwoD& other) const
 {
  return civIndex < other.civIndex;
 }

  friend class MissionPlan;

private:
  int x;
  int y;
  float civIndex;
  locationdata l;

};

In my main method , i am trying to access the private members of locationdata however i am getting an error : base operand of '->' has non-pointer type 'locationdata'

This is how i am accessing the private members

int main()
{
   list<PointTwoD>::iterator p1 = test.begin();
   p1 = test.begin();

  locationdata l = p1 ->get_locationdata();
  string sunType = l->get_sunType(); // this line generates an error

}

Upvotes: 0

Views: 181

Answers (4)

billz
billz

Reputation: 45410

This is not an issue of access privilege, get_sunType() is public already.

l is not a pointer, you could access it by . operator

update:

 string sunType = l->get_sunType(); // this line generates an error
 //                ^^

to:

 string sunType = l.get_sunType(); 
 //                ^

Upvotes: 2

Vaibhav Desai
Vaibhav Desai

Reputation: 2728

As per your code, p1 is not a reference.

Try

p1.get_locationdata()

instead of

p1->get_locationdata()

Upvotes: -1

Raxvan
Raxvan

Reputation: 6505

The operator -> has no implementation in locationdata. You need to use . operator:

string sunType = l.get_sunType();

Razvan.

Upvotes: 1

This has nothing to do with private/public. You're using the pointer-access operator -> to access the member of a class; you should be using . instead:

string sunType = l.get_sunType();

Upvotes: 2

Related Questions