-1

Suppose we have 2 versions of the same class Simple:

1.

#include <iostream>

using namespace std;

class Simple
{
public:
    Simple() { }
    Simple(int c)
    { 
        data = c;
        cout << data << endl; 
    }
private:
    int data;
};

int main()
{
    Simple obj(3);
    return 0;
}

2.

#include <iostream>

using namespace std;

class Simple
{
public:
    Simple() { }
    Simple(int c) : data(c) { cout << data << endl; }
private:
    int data;
};

int main()
{
    Simple obj(3);
    return 0;
}

Both compile, run and give the same result. Which one should be used and is there any internal difference between them? Thanks.

trollpidor
  • 447
  • 5
  • 11

1 Answers1

2

It's better to use the initializer list to initialize member variables, that's what it's there for. In the case of complex objects there may be an efficiency benefit too, since you can skip the default initialization. If the member doesn't have a default constructor, or is const or a reference, you will have no choice but to put it in the initializer list anyway.

I prefer to keep the body of a function as separate lines, in case I need to set a breakpoint on one.

Mark Ransom
  • 299,747
  • 42
  • 398
  • 622