• Advertisement
Sign in to follow this  

[C++] Question about Variable Declarations

This topic is 2090 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

This is not really a code problem I am having more of a why isn't this allowed by the C++ standard, I googled a bit but couldn't find a solution and would like to have an answer to the question.

Say we have this piece of sample code:


class SimpleTestObject
{
public:
SimpleTestObject() : a(0) {}
SimpleTestObject(int a) : a(a) {}
void print() { std::cout << a << std::endl; }
private:
int a;
};
int _tmain(int argc, _TCHAR* argv[])
{
SimpleTestObject obj();
obj.print();
return 0;
}


We get a "error C2228: left of '.print' must have class/struct/union" and to remove this error I need to remove the "()" on the line above. However if I pass a number in this constructor it compiles without complaining.
My question is why am I not allowed to called the default constructor explicitly, and more over why does the compiler think I am defining a function in a function?

Share this post


Link to post
Share on other sites
Advertisement
If it's allowed, how can you declare a function with no parameters and return an object of SimpleTestObject?

When never you write,
SimpleTestObject ThisIsAFunction();

The compiler has to treat it as an object.
Then there is no way you can write a function like that. Edited by wqking

Share this post


Link to post
Share on other sites

... [color=#282828][font=helvetica, arial, verdana, tahoma, sans-serif]

[background=rgb(250, 251, 252)]why does the compiler think I am defining a function in a function?[/background]

[/font]
[/quote]
Because according to the syntax rules of C++, that is (almost) what you are doing. To be accurate, what the compiler thinks is that you are declaring a function called "obj" which takes no parameters and returns a SimpleTestObject.

See also C++'s most vexing parse.

Share this post


Link to post
Share on other sites


...

[background=rgb(250, 251, 252)]why does the compiler think I am defining a function in a function?[/background]




Because according to the syntax rules of C++, that is (almost) what you are doing. To be accurate, what the compiler thinks is that you are declaring a function called "obj" which takes no parameters and returns a SimpleTestObject.

See also C++'s most vexing parse.
[/quote]

Yeah I have seen that link before must have forgotten about it, cheers though

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement