Initialization of variables

Jul 4, 2011 at 5:22am
Hello all,

First time poster here. Trying to learn a bit more about C++ as it helps me greatly with my UnrealScript programming.

Anyway, when looking at the "variables" topic on this site (http://www.cplusplus.com/doc/tutorial/variables/), it states:

"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?

Thanks in advance!
Jul 4, 2011 at 5:36am
No. The two initializations you show are actually identical; both call the same constructor with the same parameter.
Jul 4, 2011 at 5:38am
What is the difference between the two?


Absolutely nothing (at least for basic types)

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 
Jul 4, 2011 at 5:51am
Guys,

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!)

-Dave
Jul 4, 2011 at 7:50am
There actually is one difference which I've just stumbled upon.

When initializing a variable in the constructor of a class like this:

1
2
3
4
ClassName::ClassName(string s)
          :var(4){
....
}


You can't use var=4, you have to use var(4).
Jul 4, 2011 at 2:10pm
That is true.
Topic archived. No new replies allowed.