Chief Delphi

Chief Delphi (http://www.chiefdelphi.com/forums/index.php)
-   C/C++ (http://www.chiefdelphi.com/forums/forumdisplay.php?f=183)
-   -   Same initialization as declaration in constructor, why? (http://www.chiefdelphi.com/forums/showthread.php?t=120542)

adlasa 17-10-2013 22:18

Same initialization as declaration in constructor, why?
 
I was looking through the basic tutorial on C++ with an FRC robot.

The code:

Code:

public:
  RobotDemo(void):
      myRobot(1,2),
      stick(1)

The comments say these declarations have to be initialized in the same order as they are declared.

Why is this?

RyanCahoon 19-10-2013 11:56

Re: Same initialization as declaration in constructor, why?
 
I don't know of anything in the C++ standard that requires the member initialization list to be in declaration order. It might be some limitation of the compiler, or they might be encouraging that for code readability because the C++ standard does say that no matter the order in the initialization list, the class members will be initialized in the order they are declared in the class definition.

I don't have windriver installed so I can't check to be sure which it might be, but there's nothing keeping you from trying it out. What happens if you reverse the initializers in the example code and try to compile it?

nightpool 21-10-2013 10:00

Re: Same initialization as declaration in constructor, why?
 
Its not a requirement, but strongly recommended, as giving them a different order will lead to very unintuitive behavior, as well as a warning from GCC. As Ryan said, no matter what you put in the initialization list, the members'll be initialized in the order they are declared up above.

William Kunkel 24-10-2013 00:38

Re: Same initialization as declaration in constructor, why?
 
The reason for this is that if you want to declare a member variable as some transformation of another member variable, you can end up with declaring it before the first variable is initialized. So, if you have:
Code:

class Example {
private:
    int a;
    int b;
public:
    Example();
};

Example::Example():
    b(2), a(b+1) {
}

the value of a will not be 3, but undefined, even though it looks like it's declared after b. It's not a compiler error to have them in a different order, but it will produce a warning (I believe the warning is "warning: when initialized here").


All times are GMT -5. The time now is 12:53.

Powered by vBulletin® Version 3.6.4
Copyright ©2000 - 2017, Jelsoft Enterprises Ltd.
Copyright © Chief Delphi