jmasterx
jmasterx

Reputation: 54173

C++ classes and nested members

I'm not sure how to call this. Basically I want to make a class with nested members.

Example:

ball->location->x;
or
ball->path->getPath();

right now I only know how to make public and private members such as

ball->x;
ball->findPath();

Thanks

Upvotes: 0

Views: 149

Answers (3)

Potatoswatter
Potatoswatter

Reputation: 137930

struct Location {
    int x, y;
};

struct Path {
    vector<Location> getPath();
};

struct Ball {
    Location location;
    Path path;
};

alternately

struct Ball {
    struct Location {
        int x, y;
    } location;
    struct Path {
        vector<Location> getPath();
    } path;
};

Upvotes: 0

Thomas Matthews
Thomas Matthews

Reputation: 57749

Try this:

struct Location
{
  int x;
  int y;
};

struct Path
{
  std::string getPath();
};

struct Ball
{
  Location location;
  Path path;
};

Ball ball;
ball.location.x;
ball.path.getPath();

Or if you must use the -> operator:

struct Location2
{
  int * x;
};

struct Ball2
{
  Location2 * location;
  Path *     path;
};

Ball2  ball;
ball->location->x;
ball->path->getPath();

Upvotes: 0

alemjerus
alemjerus

Reputation: 8268

Something like this:

class Plass
{
public:
    Plass(Point *newPoint, Way *newWay)
    {
         moint = newPoint;
         bay = newWay;
         // or instantiate here:
         // moint = new Point();
         // bay = new Way();
         // just don't forget to mention it in destructor
    }
    Point *moint;
    Way *bay;
}

From here you can do:

Plass *doxy = new Plass();
doxy->moint->x;
doxy->bay->path->getPath();

Upvotes: 2

Related Questions