Reputation: 3794
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.
Upvotes: 3
Views: 1065
Reputation: 3311
A reference type is expected - just use *this
instead of this
.
A lot of compilers will warn about this anyway: myPokemon
will be constructed before trainer
is done, so it gets a reference to a non-constructed trainer
. Be careful not to call any methods on it (or use its data) since it leads to undefined behavior!
Upvotes: 4
Reputation: 993125
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.
Upvotes: 5