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