Thread: Constructor question

  1. #1
    Registered User
    Join Date
    Jan 2008
    Posts
    65

    Constructor question

    Do the member initializers of a constructor run in the order that they are listed?

    For example, can j reliably initialize to n + 1 in this example?
    Code:
    struct s {
    	int i;
    	int j;
    	s(int n)
    		: i(n), j(i + 1)
    	{}
    };

  2. #2
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,318
    No, the construction oddly enough is actually done in the order that the member variables are declared.
    What you posted would work, but this would fail:
    Code:
    struct s {
    	int j;
    	int i;
    	s(int n)
    		: i(n), j(i + 1)
    	{}
    };
    My homepage
    Advice: Take only as directed - If symptoms persist, please see your debugger

    Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

  3. #3
    and the hat of sweating
    Join Date
    Aug 2007
    Location
    Toronto, ON
    Posts
    3,545

Popular pages Recent additions subscribe to a feed