Constructor initialization list

Nov 27, 2012 at 9:04am
Hello there guys!

I would love to know what things I CAN do in the constructor's initialization list and what things I CANT do there.

lets say I have :

class Roy {
int id;
char name[10];
public:
Roy() : id(2013) , strcpy(name,"Roee") {}

I know that I cant use strcpy there and therefore I have to place it in the "body" of the constructor.
can anyone explain to me what is RIGHT to place in the initialization list then?

thanks in advance,

roy
Nov 27, 2012 at 9:08am
you can place everything what the constructor of the object (the member variable) accepts (because that is what is called)
Last edited on Nov 27, 2012 at 9:09am
Nov 27, 2012 at 10:02am
You CAN initialize member variables as coder777 says.
You CAN call constructors of member objects.
You CAN'T call any function or method, as you guess.

But let's say name is a std::string, you could write :

Roy() : id(2013), name("Roee") {}
Nov 27, 2012 at 12:53pm
You most certainly can call a function or method in the initialisation list. The function should return the value to which you want to initialise your data member. You can put any expression in an initialisation list, as long is evaluates to a value that can be used to legally initialise the data member. So, for example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
int sum(int i, int j);  // Returns the sum of the arguments

class MyCLass
{
public:

  MyClass()
  : m_value1(5) // Sets m_value1 to 5
  , m_value2(2 + 3) // The expression 2 + 3 evaluates to 5, so sets m_value2 to 5
  , m_value3(sum(2, 3)) // The expression sum(2, 3) evaluates to 5, so sets m_value3 to 5
  {
  }

private:
  int m_value1;
  int m_value2;
  int m_value3;
};


is perfectly legal. It calls the function sum, and initialises m_value3 to the number which is returned from sum.

It may or may not be safe to call a particular function in a particular initialisation list, but that depends on the circumstances.
Last edited on Nov 27, 2012 at 12:54pm
Nov 27, 2012 at 2:01pm
I know that I cant use strcpy there

Naturally, in C++ you would use a string, as already mentioned. Until C++11 there was a limitation that array members could not be initialized in the member initializer lists, but now this kind of thing is possible:

1
2
3
4
5
6
struct Roy {
    int id;
    char name[10];
public:
    Roy() : id(2013) , name{"Roee"} {}
};


(works on clang++-3.1, not yet on g++-4.7.2)
Dec 1, 2012 at 6:22am
thank you very much guys!
Topic archived. No new replies allowed.