0
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?

5
  • 4
    The first point is wrong: The default constructor is not called. (There is no default constructor.) Commented Nov 12, 2014 at 13:58
  • 2
    What makes you think a default constructor is called? Commented Nov 12, 2014 at 13:58
  • 1
    You can easily test it, print some lines to the console to answer your questions. Commented Nov 12, 2014 at 13:59
  • 1) no default constructor is available to be called (as you didn't provide one). 2) t(3) is explicitly calling the int x constructor anyway so it wouldn't happen even if there was a default constructor. Commented Nov 12, 2014 at 13:59
  • @JosephMansfield misunderstanding a C++ book make me "think a default constructor is called". Sorry for that. thx. Commented Nov 12, 2014 at 14:14

3 Answers 3

2
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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

0

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).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.