songhir
songhir

Reputation: 3583

cpp default constructor and member initialization list?

class test
{
public:
    test(int x)
    {
        val = x;
    }
private:
    int val;
};

test t(3);

I got 2 points about this code.

  1. test t(3)would call default constructor first, then do val = 3

  2. if there is at least a user-defined constructor, then the compiler does not generate an implicit default constructor

is there a contradiction?

Upvotes: 0

Views: 115

Answers (3)

Mike Seymour
Mike Seymour

Reputation: 254431

test t(3) would call default constructor first, then do val = 3

No default constructor is called. val is default-initialised before the test constructor body; if val were a type with a default constructor, then that constructor would be called. But int doesn't have a constructor, and default-initialising just leaves it in its uninitialised state with an indeterminate value.

Perhaps you were thinking that this might call the default constructor of test. It doesn't; no constructor of test would do that, unless you explicitly delegated to that constructor.

if there is at least a user-defined constructor, then the compiler does not generate an implicit default constructor

That's correct, declaring any constructor prevents the implicit default constructor.

is there a contradiction?

No. test doesn't have a default constructor, but nothing here tries to use such a thing.

Upvotes: 1

Ips
Ips

Reputation: 369

No, custom constructor doesn't call parameterless constructor, so it is not contradiction.

You're probably mixing two things together - every constructor calls a base class constructor (either default, or some else if you specify the arguments).

Upvotes: 0

ravi
ravi

Reputation: 10733

test t(3);

is calling your parametrized constructor( with argument as 3 ) not default constructor. And yes if you define a single constructor with parameter then compiler won't generate dfault constructor.

Upvotes: 2

Related Questions