I’m a bit confused with these C++ pointers and I would like to know if it’s possible to create a pointer inside a constructor that will point to the instance of the class (something on the lines of the following).
class Room{
public:
Room();
~Room();
private:
Room* ptrToSelf;
};
Room::Room(){
ptrToSelf = &(what should I write in here to have the pointer point to it)
}
I know this might sound crazy (newbie here), but I just wanted to know if it is possible. Could someone please explain this to me.
Many thanks
Edit:
Thank you everyone for answering me so fast. I was asking because I wanted to use a public Room*::getPointer(); method to return the pointer for the class. I have a character that moves from room to room and I’m using pointers to achieve this. I’m getting the input from the user in form of string and I can’t pass that string to the function to character.moveTo(const Room*) method I created. I need a way to “convert” the string into a pointer for the class so that I could pass the pointer to the method.
Edit:
I was thinking of implementing a method that will return the pointer for the object based on a string type parameter:
Room::Room* getPointer(const string &nameOfRoom){
//I can't use this return statement as the following error
//Error: 'this' may only be used inside a nonstatic member function
return this;
Edit (hopefully last one):
Is this returning what I’m looking for?
Room::Room* getPointer(const string &nameOfRoom){
return &Room();
}
or it’s returning the address of a new Room?
Thank you
Just use the implicit
thisparameter:Or, even better (ignoring the fact that
ptrToSelfis a rather silly idea to begin with):EDIT: @BenjaminLindley drew my attention to the fact that there will be issues with certain other member functions. In particular, the copy constructor won’t behave correctly by default (
ptrToSelfwill simply be copied from the source instance, so both instances will end up pointing to the one). You may therefore need to provide a copy constructor that ensuresptrToSelfis assigned correctly. The base case is this:You also need to worry about the assignment operator, but as long as it simply invokes the copy constructor, you’ll be fine. The following general-purpose implementation will do the trick:
(P.S.: It should be
class Room {…, notclass Room(){….)