[C++] Question about Variable Declarations

Started by
2 comments, last by NightCreature83 11 years, 10 months ago
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?

Worked on titles: CMR:DiRT2, DiRT 3, DiRT: Showdown, GRID 2, theHunter, theHunter: Primal, Mad Max, Watch Dogs: Legion

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.

https://www.kbasm.com -- My personal website

https://github.com/wqking/eventpp  eventpp -- C++ library for event dispatcher and callback list

https://github.com/cpgf/cpgf  cpgf library -- free C++ open source library for reflection, serialization, script binding, callbacks, and meta data for OpenGL Box2D, SFML and Irrlicht.


... [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.



...

[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

Worked on titles: CMR:DiRT2, DiRT 3, DiRT: Showdown, GRID 2, theHunter, theHunter: Primal, Mad Max, Watch Dogs: Legion

This topic is closed to new replies.

Advertisement