PDA

View Full Version : What default constructor?



bitChanger
15th February 2006, 19:24
imagine the following sudo like code

class A
{
A();
A(int, int);
};

main
{
A varname; // no problem
A varname(1, 2); // no problem

A varname(); // problem !!!
}

Why can't you use the so called optional parenthesis in this example?

My first thought was the compiler sees this as invalid chars for the variable name, but this compiles.

So i added a line after the problem statement using the varname and then it won't compile.

This leaves me to beleive that the compiler just ignores the problem statement if you don't acually use it. By the way this is the same for g++ as well as msvc compilers.

So, is there a good reason why this won't just call the default constructor?

Just curious ... :)

Codepoet
15th February 2006, 19:29
A varname();
Is a declaration of a function which has no parameters, returns "A" and is called varname ;)
Everything which looks like a function IS A function

wysota
15th February 2006, 19:30
"A varname();" is a declaration of a varname function returning A.

Edit: Great, someone was a bit faster :)

bitChanger
15th February 2006, 20:06
So why is it that:

A varname(1,2);

is not a declaration of a function, but instead calls a function constructor and assigns the new instance to a variable called varname.

jacek
15th February 2006, 20:44
is not a declaration of a function, but instead calls a function constructor and assigns the new instance to a variable called varname.
Because you can't specify values in declarations this way.

This would be a declaration:
A function1( int, int );
A function2( int a, int b );
A function3( int a = 1, int b = 2 );

bitChanger
15th February 2006, 20:50
Got it. Thanks! :)