"The first one, known as c-like initialization, is done by appending an equal sign followed by the value to which the variable will be initialized:
type identifier = initial_value ;
For example, if we want to declare an int variable called a initialized with a value of 0 at the moment in which it is declared, we could write:
int a = 0;
The other way to initialize variables, known as constructor initialization, is done by enclosing the initial value between parentheses (()):
type identifier (initial_value) ;
For example:
int a (0);
Both ways of initializing variables are valid and equivalent in C++."
My question is: What is the difference between the two? Is there a benefit or pitfall to using one over the other?
Is there a benefit or pitfall to using one over the other?
Nope.
The only difference is when you get into classes and constructors. Using the parenthesis approach makes it easier to choose which constructor you want:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
class Example
{
public:
Example(int); // (A) a ctor that takes 1 int...
Example(int,int); // (B) a ctor that takes 2 ints
};
//...
Example e(5); // calls ctor A
Example f = 5; // also calls ctor A
Example g(1,2); // calls ctor B
Example h = Example(1,2); // also calls ctor B
Thank you very much for the clear answers. I as initially confused, and just wanted to verify that what I was thinking was correct. Great forum, you'll certainly see more around here more often (and with a bunch of questions!)