constructor with one default parameter
Asked Answered
B

3

7

Suppose I have a class

class C {
       C(int a=10);
};

why if I call

C c;

the contructor C(int =10) is called and if I call

C c();

the default constructor is called? How to avoid this? I want to execute only my constructor, I tried to make the default constructor private, but it doesn't work.

Bacteroid answered 24/10, 2010 at 19:37 Comment(2)
How about your provide us with a compilable piece of code that shows us the behavior you believe you're seeing? As you can see from the answers so far, what you describe is not what the code should do.Anthropogeography
Just as an FYI, MSVC (since at least VS2003) will provide a warning about this problem: warning C4930: 'C c(void)': prototyped function not called (was a variable definition intended?) I know other compilers will as well, but the ones I have readily available at the moment don't.Piddock
A
17
  1. Actually, C c(); should be parsed as a function declaration. In order to explicitly invoke the default-constructor, you need to write C c = C();.
  2. Once you define any constructor, the compiler will not provide a default-constructor for your type, so none could be called.
  3. Since your constructor can be invoked with one argument, it serves as an implicit conversion function. You should consider making it explicit, to prevent implicit conversions from kicking in at unexpected moments.
Anthropogeography answered 24/10, 2010 at 19:39 Comment(0)
F
14

The code C c(); doesn’t do what you think it does:

It declares a function called c that takes no arguments and returns a C. It is equivalent to

C c(void);
Ferrick answered 24/10, 2010 at 19:39 Comment(1)
The important thing being that it does nothing (in terms of runtime behavior).Piddock
G
1

This is because the c() is interpreted as a function named c. C() will trigger the appropriate constructor for the C class

Granville answered 24/10, 2010 at 20:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.