Skip to main content
gamedev.net
🔒 Locked

class member initialisation list

Started by ChaosEngine May 14, 2003 at 3:15 AM 4 replies 300+ views
Original Post
ChaosEngine
ChaosEngine
ok this came up with one of my colleagues code today. we have class CA and class CB class CB requires a reference to a CA object in it's constructor so
      

class CA
{
    CA() {};
    // nothing special 

};

class CB
{
    CB(CA& a)
    : m_aref(a){};

    CA& m_aref;
}
  
  
all fine and good. until we have class CC which aggreates CA and CB.
        
class CC
{
    CC();

private:
    CA a_object;
    CB b_object;
};
   
so my question is: can b_object be constructed with a reference to a_object i.e.
   
CC::CC()
: b_object(a_object)
{

}
      
it seems to work, but is it standard or some weird behaviour of the msvc.net compiler. edit: Obviously lang is C++ and yes, I know it's bad design, I'd just like to know if it'll work. Cheers "That's not a bug, it's a feature!" --me [edited by - ChaosEngine on May 14, 2003 4:15:46 AM] [edited by - ChaosEngine on May 14, 2003 4:16:37 AM]
if you think programming is like sex, you probably haven't done much of either.-------------- - capn_midnight
Qw3r7yU10p!
Qw3r7yU10p!
Yes, it''s based on the order in the class declaration not the order in the initialisation list.
ChaosEngine
ChaosEngine
Thanks. That''s what I thought.

"That''s not a bug, it''s a feature!"
--me
if you think programming is like sex, you probably haven't done much of either.-------------- - capn_midnight
JohnBolton
JohnBolton
When CC''s constructor starts, the CC object has been instantiated, so a reference to a member variable is valid immediately. Since CB() just stores a reference to a_object, there are no issues with order of execution.
John BoltonLocomotive Games (THQ)Current Project: Destroy All Humans (Wii). IN STORES NOW!
Qw3r7yU10p!
Qw3r7yU10p!
quote:
Original post by Jambolo
When CC''s constructor starts, the CC object has been instantiated, so a reference to a member variable is valid immediately. Since CB() just stores a reference to a_object, there are no issues with order of execution.


This thread was going so well.

The initialisation list allows you to pass any necessary arguments to member variables. This is part of the construction of the whole object. When you pass the reference to the a_object into b_object''s constructor that is because b_object has not yet been created. The a_object has to have been created first for you to pass a reference to its memory location. You have to do things in the correct order.

If the constructor throws an exception it is as if the object never existed. The object can only be considered instantiated after successfully leaving the constructor.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.