C++ Struct constructor problem

Recommended Posts

Hello all, I have a little problem that's been nagging me, and I'm hoping somebody could shed some light on it. I have a simple struct declared/defined as so:
struct XFileInfo
{
XFileInfo()
: is32BitFloat( false ),
isText( false )
{}

bool is32BitFloat;
bool isText;
};

And then I create an instance of this struct on the stack within a function like this:
void XFileLoader::LoadTemplatesFromFile( const char* filename )
{
std::ifstream xFile( filename );

XFileInfo info();
if (!ValidateXFile( xFile, info ))
{
// invalid X file
return;
}

}

But the problem is, I get the following error from the VS compiler: 1>.\XFileLoader.cpp(28) : error C2664: 'ValidateXFile' : cannot convert parameter 2 from 'XFileInfo (__cdecl *)(void)' to 'XFileInfo' 1> No constructor could take the source type, or constructor overload resolution was ambiguous I'm not sure what the issues are with constructor overload resolution here. I defined a single default constructor, what is the ambiguity? Or is this a symptom of something completely different? Thanks much for any advice!

Share on other sites
XFileInfo info(); <-- Function declaration (note: declaration, not definition).
XFileInfo info; <-- variable declaration and construction.

Share on other sites
This line:
XFileInfo info();

This is a function declaration. C++ allows functions to be declared inside other functions. You can rewrite it as:
XFileInfo info;

Which is does call the constructor.

Share on other sites
I see, so if I had arguments to pass in it would be treated as a constructor call, but if I have no arguments and just parentheses it assumes that this is an inline function declaration. Is this correct?

Share on other sites
Yep, because then it couldn't be a function declaration. One of the rules in C++ parsing is along the lines of "if it can be a function declaration, parse it as such"

Create an account

Register a new account

• Forum Statistics

• Total Topics
628278
• Total Posts
2981785

• 10
• 11
• 17
• 13
• 9