C ++: Passing object object reference to constructed member objects?

Ok, consider the following classes:

class Object { public: // Constructor Object() : [Initialization List] { ... } ... }; class Container { public: Object A; Object B; .... Container() : [Initialization List] { } }; 

I would like to provide [access to the container and its members] to the objects.

My first thought was to somehow pass a reference to the current Container object to the object constructors. But I can’t figure out how to do this.

I mixed up with "this", but I get nothing. I tried something like this:

 class Object { public: Container& c // Constructor Object(Container& c_) : c(c_) { ... } ... }; class Container { public: Object A; Object B; .... Container() : A(Object(this)) B(Object(this)) { } }; 

My ultimate goal is to have access to object B from inside the member method of object A.

Does anyone have an idea on how to get closer to what I'm looking for?

Thanks!

+4
c ++ inheritance reference
source share
3 answers

This is not UB or bad, you must use this in the list of initializers, although help is required, and your code works fine with minor changes.

 class Container; class Object { public: Container& c // Constructor Object(Container& c_) : c(c_) { } }; class Container { public: Object A; Object B; Container() : A(Object(*this)) B(Object(*this)) { } }; 

this is a pointer, you need a link, and a simple de link will do the trick. This is a completely legal and specific code. What is not allowed is access to any data items or functions through a pointer, because that data or member functions simply cannot exist until the initialization list is complete. But it is definitely allowed to take a pointer or a reference to an object during its list of initializers and pass it.

+5
source share

How about using pointers? Edit : fixed code to avoid this in the initialization list.

 class Container; class Object { public: Container *c; // Constructor Object(Container *c_) : c(c_) { } }; class Container { public: Object *A, *B; Container() { A = new Object(this); B = new Object(this); } }; 
+1
source share

You do not have to pass this to the initializers for the members of the class you are instantiating, but you can pass it later, so there are two easy ways to solve your problem

  • use the object installer ( A.setContainer(*this) ) in the constructor body
  • make pointers A and B, initialize them to NULL and execute A = new Object(this) in the constructor body
-one
source share

All Articles