Search code examples
c++constructorreferenceinitialization-list

Pass 'this' object to an initialization list


I've reduced the problem down to the following sample code:

class Charizard { //truck
    trainer &myTrainer;
  public:
    Charizard(trainer &tMyTrainer);
};

class trainer {
    Charizard myPokemon;
  public:
    trainer();
};

Charizard::Charizard(trainer &tMyTrainer) : myTrainer(tMyTrainer) {}

Without changing or adding public members, how can I create the constructor for trainer, such that when myPokemon is created in the initialization list, the "myTrainer" points back to the trainer being created?

Here is what I tried:

trainer::trainer() : myPokemon(this) {}

But of course "this" is not the correct type. I cannot change what the Charizard constructor takes in (it's a public member), so I'm not sure what to do. Any ideas?

Note: Title might need some work.


Solution

  • If you need an instance object instead of a pointer, try:

    trainer::trainer() : myPokemon(*this) {}
    

    Be careful if Charizard tries to call any methods on tMyTrainer in its constructor, because your new trainer object has not yet been fully constructed at that time.