Reputation: 6442
There are at least two ways to initialize a class in C++.
(1) Initializer List
struct C
{
int i;
C() : i(0) {}
};
(2) Initializer Method
struct D
{
int i;
C() { init(); }
void init() {
i = 0;
}
};
I need to re-init objects of my class from time to time. With the second solution, I can simply call obj.init()
. With the first solution, I would either have to add an init()
function which essentially duplicates the initializer list effect or use obj = C()
.
Is there a more-or-less consensus on what variant is better here? Is there a disadvantage to using an initializer method (except the possible loss of performance as mentioned in the C++ FAQ).
Upvotes: 2
Views: 1007
Reputation: 70931
When creating an array (using vector, or allocating dynamically using new
) you will have to explicitly call init
on each of its members while using a constructor, it will automatically be called for all elements.
I prefer placing basic initialization into the constructor and more complex logic into an init method. In my opinion a constructor should not perform any complex operations.
Upvotes: 5
Reputation: 1
Below are the scenarios when initializer list is used:
Upvotes: 0
Reputation: 42083
The main difference is that without using initialization list, members are created and then values are assigned to them. When you use initialization list, members are directly created by using given values.
One of situations, when using initialization is important, is when your class holds some references as a members and it is necessary to initialize these members right when they are being constructed:
class A
{
public:
A(B& bRef) : bRef_(bRef) { }
private:
B& bRef_;
}
This question could help you too: In this specific case, is there a difference between using a member initializer list and assigning values in a constructor?
Your init()
method is perfectly fine. As you yourself have mentioned, you want to initialize these members more times than just first time when the instance of this class is being constructed, so for the sake of reusability and simplicity it's right to keep it in a method. Don't try to improve performance of your code unless you really need it.
Some people say that It's easier to make a correct program fast than it's to make a fast program correct. ;)
Upvotes: 6