difference between MyClass a(); and MyClass a;

G

Gunnar G

What is the difference between the two lines in the main function?

class MyClass{ ....};

int main(){
MyClass a();
MyClass a;
}
 
V

verec

Look it up. It's in section 10 of the FAQ:
http://www.parashift.com/c++-faq-lite/

(Hint: what does "int foo();" mean to you?)

I for one, would have gladly traded that "C compatibility" quirk,
and happily lived in a world where C++ would have disallowed function
delclarations _within_ function definitions ...

Stroustrup once wrote that "C arrays are broken beyond repair", and
I'm quite close to think the same holds for C++ ... beyond repair.

Not to say that C++ is useless, or whatever, just unncessarily
inconsistent, as soon as you start looking at the details.

I wish Stroustrup had come up with: "--C" instead :)
 
H

Howard

verec said:
I for one, would have gladly traded that "C compatibility" quirk,
and happily lived in a world where C++ would have disallowed function
delclarations _within_ function definitions ...

Stroustrup once wrote that "C arrays are broken beyond repair", and
I'm quite close to think the same holds for C++ ... beyond repair.

Not to say that C++ is useless, or whatever, just unncessarily
inconsistent, as soon as you start looking at the details.

I wish Stroustrup had come up with: "--C" instead :)

I don't see what the problem is here. The following is a normal function
prototype:

int foo();

How else would you declare a function foo that returns an int?

Likewise, the following is also simply a function prototype:

MyClass foo();

Again, how else could you declare a function foo that returns a MyClass
object?

There's no "C compatibility quirk" here that I can see. It's perfectly
logical, and consistent.

You just need to learn to read "MyClass foo;" as a variable declaration and
"MyClass foo();" as a function declaration. The parentheses tell you that.

Whether or not the syntax is allowed inside another function is irrelevant.
You wouldn't want a function prototype to suddenly be seen as a variable
declaration just because it's inside a function, would you? THAT would be
inconsistent and confusing!

Now granted, there ARE situations where the distinction may not be so easily
seen. (See FAQ 10.19 for example.) But I'd hardly say C++ is "broken
beyond repair". It just takes a while to learn the details. You can always
use Delphi or C# if you don't like C++. Of course, you'll probably need to
look for a new job... :)

-Howard
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,756
Messages
2,569,535
Members
45,008
Latest member
obedient dusk

Latest Threads

Top