1

Possible Duplicates:
Why should I prefer to use member initialization list?
C++ - what does the colon after a constructor mean?

here is following code

class vector2d {
public:
  double x,y;
  vector2d (double px,double py): x(px), y(py) {}

i dont understand this line

 vector2d (double px,double py): x(px), y(py) {} 

is it same as vector2d(double px,double py){ x=px;y=py;}? or?

Community
  • 1
  • 1
  • 1
    cf. ["Should my constructors use "initialization lists" or "assignment"?"](http://www.parashift.com/c++-faq-lite/ctors.html#faq-10.6) – James McNellis Jul 18 '10 at 17:52
  • 1
    Duplicate of [Why should I prefer to use member initialization list?](http://stackoverflow.com/questions/926752/why-should-i-prefer-to-use-member-initialization-list) – James McNellis Jul 18 '10 at 17:56
  • 1
    And duplicate of [C++ - what does the colon after a constructor mean?](http://stackoverflow.com/questions/2785612/c-what-does-the-colon-after-a-constructor-mean) which links to more duplicates. – GManNickG Jul 18 '10 at 18:02

1 Answers1

0

Yes, it's the same in your example. However, there's a subtle difference: x(px) initializes x to px, but x=px assigns it. You'll not know the difference for a doublevariable, but if x where a class there would be a big difference. Let's pretend that x is a class of type foo:

x(px) would call the foo copy constructor, foo::foo(foo &classToCopyFrom).

x=px on the other hand, would first call the foo default constructor, then it would call the foo assignment operator.

This is a good reason that you should prefer x(px) in most cases.

John Reynolds
  • 4,927
  • 4
  • 34
  • 42