Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ class friend

I'm trying to compile such code:

#include <iostream>
using namespace std;

class CPosition
{
  private:
    int itsX,itsY;
  public:
    void Show();
    void Set(int,int);
};

void CPosition::Set(int a, int b)
{
  itsX=a;
  itsY=b;
}

void CPosition::Show()
{
    cout << "x:" << itsX << " y:" << itsY << endl;
}

class CCube
{
  friend class CPosition;
  private:
         CPosition Position;
};

main()
{
  CCube cube1;

  cube1.Position.Show();
  cube1.Position.Set(2,3);
  cube1.Position.Show();
}

but get 'CCube::Position' is not accessible in function main() 3 times. I want class CPosition to be declared outside CCube so that I can use it in future in new classes e.g. CBall :) but how can I make it work without using inheritance. Is it possible :)?

Regards, PK

like image 645
Moomin Avatar asked Jun 26 '26 17:06

Moomin


1 Answers

In addition to the normal getter you should also have a const getter.
Please note the return by reference. This allows you any call to SetXX() to affect the copy of Position inside CCube and not the copy that you have been updating.

class CCube
{
    private:
        CPosition Position;
    public:
        CPosition&       getPosition()       { return Position; }
        CPosition const& getPosition() const { return Position; }
};
like image 159
Martin York Avatar answered Jun 28 '26 05:06

Martin York



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!