1

i searched but could not find the answer.

So I have my c++ constructor:

MyClass(string username = "something");

note this is the only constructor I have.

in my main, I do:

MyClass one();
MyClass two = MyClass();

are these two expressions equivalent? is the compiler gonna call my constructor with the default string, or is it gonna call the default (empty) constructor?

What would change if I did have a constructor MyClass(); ? I guess that would not compile, right?

Prasoon Saurav
  • 91,295
  • 49
  • 239
  • 345
Edoz
  • 1,068
  • 1
  • 11
  • 16
  • `MyClass one();` [Refferred to as the most Vexing parse](http://stackoverflow.com/questions/1424510/most-vexing-parse-why-doesnt-a-a-work) Its not actually a declaration of the variable one. But a forward declaration of a function called one. – Martin York Mar 19 '11 at 07:27

5 Answers5

4

MyClass one();

This declares a function one returning a MyClass object and taking no arguments.

If you have both default constructor (of the form MyClass()) and default argument constuctor (of the form MyClass(string s = "string") ) which one would be called if you don't pass any argument?

For example this would not compile

class MyClass
{
  public:
   MyClass(std::string username = "something") {}
   MyClass(){}
};

int main()
{
   MyClass one();
   MyClass two = MyClass(); //ambiguous call here
}
Prasoon Saurav
  • 91,295
  • 49
  • 239
  • 345
2
MyClass one;
MyClass two = MyClass();

If this is what was meant then one and two will call the same constructor, which happens to be your constructor, which happens to be the only constructor.

travis
  • 31
  • 1
0

It will call your constructor. If you define a constructor yourself--any constructor regardless of the number of arguments--the compiler will not generate a default constructor.

[edit] As Prasoon Saurav says, MyClass one(); declares a function. You want MyClass one;, note: no parentheses.

dappawit
  • 12,182
  • 2
  • 32
  • 26
0

The expressions will have the same nett effect, but the aren't strictly equivalent. The first calls your constructor on one. The second constructs a temporary and then assigns it to two, thus invoking the class's copy-constructor.

Marcelo Cantos
  • 181,030
  • 38
  • 327
  • 365
0

are these two expressions equivalent?

They are not equivalent.

MyClass one();

it is function one(), return MyClass.

if you want to declare object of MyClass, It should be:

MyClass one;

or

MyClass one = MyClass();

for question:

is the compiler gonna call my constructor with the default string, or is it gonna call the default (empty) constructor?

if you declare your own constructor, compiler will never generate default constructor, then there is no default constructor now. for example:

MyClass(string username); // declare constructor take 1 parameter
MyClass three; // error, no matching constructor
the boy
  • 235
  • 1
  • 6