| evolver (11) | |
|
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 | |
|
|
|
| coder777 (2549) | |
| you can place everything what the constructor of the object (the member variable) accepts (because that is what is called) | |
|
Last edited on
|
|
| SKZ81 (6) | |
|
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") {} | |
|
|
|
| MikeyBoy (235) | |||
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:
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
|
|||
| Cubbi (1925) | ||||
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:
(works on clang++-3.1, not yet on g++-4.7.2) | ||||
|
|
||||
| evolver (11) | |
| thank you very much guys! | |
|
|
|