Initialization Lists

Do initialization lists get called before or after the function logic.

1
2
3
4
5
6
7
8
9
10
11
12
13
template <class T>
myAnimal::myAnimal(const myAnimal & rhs) : legs(rhs.legs), eyes(rhs.eyes)
{
   if(legs < 6) { // I want legs == rhs.legs
      
     
       // Do stuff
 
   }
}
// I'm scared rhs.legs == legs only after the function logic.

Before.

Also note that the variables are initialized in the order they are defined in the class definition and not in the order they are listed in the initialization list.
Last edited on
Consider this:
1
2
3
4
5
6
7
struct Gaz {
  std::vector<int> v;
  Gaz()
  {
    // Can v be used here?
  }
};

The answer is yes; the member object v has been constructed before the function body.

Or this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
struct Foo {
  Foo( int x ) {
    std::cout << "Foo " << x <<'\n';
  }
};

struct Bar {
  Foo z;
  Bar( int y )
  : z( y )
  {
    std::cout << "Bar\n";
  }
};

What is the order of the outputs?

The constructor of Foo is called during the initialization.
Also note that the variables are initialized in the order they are defined in the class definition and not in the order they are listed in the initialization list.


Did not know that. Thanks!



And FooBar.
Topic archived. No new replies allowed.