0

While I was working in c++ I see two type of ctor definition.. Is there any difference while assigning value? Does one of them has advantages or just writing style ?

1st ctor definition:

class X
{
public: 
    X(int val):val_(val){}
private:
    int val_;
};

2nd ctor definition:

class X
{
public: 
    X(int val)
    {
       val_ = val;
    }
private:
    int val_;
};
Barry
  • 286,269
  • 29
  • 621
  • 977
goGud
  • 4,163
  • 11
  • 39
  • 63

3 Answers3

3

Technically yes, although you can typically not observe any difference for built-in types like int.

The difference is that your first snippet copy-constructs val_ from val, while the second one default constructs val_ and then assigns val to it. As I said above, this usually only matters for more complex types whose constructors actually do work.

A simple example which demonstrates the difference would be

class X
{
public: 
    X(int val):val_(val){}
private:
    const int val_;
};

which compiles vs.

class X
{
public: 
    X(int val)
    {
       val_ = val;
    }
private:
    const int val_;
};

which does not.

Baum mit Augen
  • 49,044
  • 25
  • 144
  • 182
1

Yes there is a difference. In a constructor initializer list, the member variables are constructed, while the assignments in the constructor body is assignments to already constructed variables.

For the basic types like int or float it's no actual difference though.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
0

In your example, there is no difference. Since your member is an int, the two statements have the same effect.

If your member variable was an object, the first form would be better, because it would simply call the constructor of the object class, while the second form would create an object by using the default constructor, then create another, store it into a temporary, call the destructor on the first object, copy the temporary into your member variable, call the destructor again on the second object.

G B
  • 2,951
  • 2
  • 28
  • 50