954,504 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

which one is better

Hi
I would like to know which is better. inialise a value like

int i=0;


or like this.

int i(0);

and why.

masa
Light Poster
29 posts since Dec 2005
Reputation Points: 10
Solved Threads: 1
 

For native types I don't think it makes a difference. For user-defined types I think it may mean the difference (if any) between calling (the default constructor and [probably not in this case?]) the assignment operator and a copy constructor.

Real C++ people...?

Dave Sinkula
long time no c
Team Colleague
5,058 posts since Apr 2004
Reputation Points: 2,780
Solved Threads: 314
 

>I would like to know which is better.
There's no difference if they both compile (they might not for user-defined types), pick which you find more intuitive.

>Real C++ people...?
I don't think I count as a real C++ person, but both call the primary (non-copy) constructor. The only noticeable difference would be if the constructor in question is defined as explicit, in which case an implicit argument would be illegal:

class test1 {
public:
  test1 ( int init ) {}
};

class test2 {
public:
  explicit test2 ( int init ) {}
};

int main()
{
  test1 a1 ( 0 );
  test1 b1 = 0;
  test2 a2 ( 0 );
  test2 b2 = 0; // This will cause an error
}
Narue
Bad Cop
Administrator
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401
 

thank you everyone for the answer

masa
Light Poster
29 posts since Dec 2005
Reputation Points: 10
Solved Threads: 1
 
kon_t
Newbie Poster
17 posts since Feb 2005
Reputation Points: 10
Solved Threads: 2
 

Thanks, I needed that.

Dave Sinkula
long time no c
Team Colleague
5,058 posts since Apr 2004
Reputation Points: 2,780
Solved Threads: 314
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You