shinzou
shinzou

Reputation: 6192

Default initialize data members that are objects?

Why do you have to initialize object data members in the constructor and you can't default initialize them like with primitive types? Is it possible to initialize them like with primitive types?

Here's an example:

class foo {
    int a;
public:
    foo(int _a) :a(_a) {};
};

class bar {
    string a = "asdf";//no error
    int num = 1;//no error
    foo x(1); //error, why?
    foo z;
public:
    bar(): z(1){}//no error
};

Upvotes: 2

Views: 81

Answers (2)

g24l
g24l

Reputation: 3125

Permitting direct-initialization in class-definition would lead to difficulties in distinguishing from function declarations:

Consider:

struct k;

struct foo { foo(int x = 1){} };

class toto
{
static constexpr int k = 1;
foo x(1); // hm might be ok...
foo y(); // hm ... NOK , what y is ? an object or a function declaration?!?!
foo z(k); // problem .... this seems a fucntion definition?!!!
foo z{k}; // clear it is not a function definition
};

The proper way to do this is either:

foo f= 1;

or

foo f{1};

or

foo f = {1};

Upvotes: 2

Baum mit Augen
Baum mit Augen

Reputation: 50063

In-class initializers only work with the operator= syntax or with brace-initializer lists, not with the function style initialization. So

foo x{1};

instead of

foo x(1);

should do the trick.

In your case, you could also use

foo x = 1;

but that would break if foo's constructor taking a single int was explicit.

Upvotes: 6

Related Questions