HossamHoussien HossamHoussien - 1 month ago 9
C++ Question

How to return a pointer of a class member from a function

I have created class called

Room
as follows

#ifndef ROOM_H
#define ROOM_H
#include <string>

class Room
{
private:
std::string name;
std::string description;
Room* south;
Room* north;
Room* east;
Room* west;
public:

//CONSTRUCTOR
Room();
Room(std::string name, std::string desc);

//METHODS
std::string getName();
std::string getDescription();
void link(Room *r, std::string direction);
Room *getLinked(std::string direction);
void printLinked();

~Room();


};

#endif // ROOM_H


/*************************************************************************/

void Room::link(Room *r, std::string direction)
{

if (direction == "south")//THIS IS JUST FOR TEST
{
this->south = this->getName();
}
}
/*************************************************/
Room Room::*getLinked(std::string direction)
{
return south;
}


And here is my question in
getLinked
method how can I return the pointer (e.g.
south
,
north
,
east
,
west
)

Answer

Are you actually asking what's the correct definition syntax for the Room::getLinked() function is?

Well, here you go:

Room* Room::getLinked(std::string direction) {
    if(direction == "south") {
        return south;
    }
    // ... the other directions
    return nullptr;
}