Pass the 'this' object to the initialization list

I reduced the problem to the following code sample:

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 elements, how can I create a constructor for a trainer, for example, when myPokemon is created in the initialization list, "myTrainer" points to the trainer being created?

Here is what I tried:

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

But of course, "this" is not the right type. I can't change what the Charizard constructor accepts (it's an open member), so I'm not sure what to do. Any ideas?

Note. The title may require some work.

+3
source share
2 answers

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

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

, Charizard tMyTrainer , trainer .

+5

- *this this.

: myPokemon trainer, trainer. , - ( ), undefined!

+4

Source: https://habr.com/ru/post/1778548/


All Articles