Object Composition

I am wondering if someone could display a very simple example of using references vs. pointers for object composition. I am still a little confused.

Here's an example of what I'm describing in Ruby for brevities sake:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Brain
   attr_accessor :man
   def initialize(m)
      :man = m
   end
end

class Man
   attr_accessor :brain
   def initialize(b)
      :brain = b
   end
end

m = Man.new()

m.brain          # mans brain
puts m.brain.man # self 


I realize in ANSI C you would just use pointers, but I am choosing to use references since my embedded objects will be permanent. I also prefer the dot ( . ) operator as well vs. the (->) pointer notation.

Would someone be willing to provide a concise example of the above Ruby in C++?

I have a strong C background, however I don't fully understand constructors in the C++ language. I have reviewed initializer lists but do not know how to use them in this context. I imagine what I am looking for is trivial at best, but I can't seem to find a straight forward example in my personal library.

Thank you!
Last edited on
You mean
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
struct Brain{
   struct Man& man;

   Brain( Man& m ) : man(m) {}

   void do_brain_stuff(){}
};

struct Man{
   Brain brain;

   Man() : brain( *this ) {}

   void do_man_stuff(){}
};

int main(){
   Man m;
   m.brain.do_brain_stuff();
   m.brain.man.do_man_stuff();
   return 0;
}
?
Thank you, I see now.

*this is the self reference, as where this is just the pointer to the reference.

Splendid!
Topic archived. No new replies allowed.