Ive been programming for sometime now so Im not a complete beginner but I just encountered a problem I don't understand.
I was getting the following error:
In file included from inc/Board.hpp:8:0,
from main.cpp:5:
inc/TemplateLoader.hpp: In member function ‘std::vector<{anonymous}::ChessPiece> {anonymous}::TemplateLoader::getPiecesData()’:
inc/TemplateLoader.hpp:72:8: error: request for member ‘setCoordinates’ in ‘{anonymous}::cp’, which is of non-class type ‘{anonymous}::ChessPiece({anonymous}::ChessPiece::Color_t, {anonymous}::ChessPiece::Type_t)’
class TemplateLoader
{
// ... Constructos / Destructors not shown
std::vector<ChessPiece> getPieceData()
{
std::vector<ChessPiece> pieces;
// there is a for loop here (which is omitted to save me from typing...) it contains the following:
ChessPiece cp(ChessPiece::Color_t(c), ChessPiece::Type_t(t)); // Just an example, the color and type values are pulled from variables that are a part of the TemplateLoader class
cp.setCoordinates(x, y, z); // again just an example but produces the same error
pieces.push_back(cp);
// end for loop
return pieces;
}
};
I fixed the error by changing the TemplateLoader.hpp class's getPieceData() function to:
1 2 3 4 5 6
// once again, lazy and dont want to type out the class again
std::vector<ChessPiece>* TemplateLoader::getPieceData()
{
// inside for loop...
ChessPiece cp = ChessPiece(ChessPiece::Color_t(c), ChessPiece::Type_t(t)); // Suddenly the error is gone and my program compiles all because I used the operator = in construction rather than constructing the class normally...
}
My code now compiles and works fine. Although it is far from pretty or in use of good programming practices (everything I know is self taught so yeah... Any suggestions on improving my programming are welcome by Im mostly interested in the title question.)
What I don't understand is why it was giving me that error in the first place and why my solution solved it. Please explain, thank you.
Oops sorry, that was a typo, It would have given me an error like: expected ')' before ';' if that was my problem. (The typo didn't exist in my actual code.)
The error message is saying that there is no member called "setCoordinates" in the function called "cp" (because functions are non-class types)
ChessPiece cp(ChessPiece::Color_t(c), ChessPiece::Type_t(t)); // Just an example
That's a function declaration (if you don't see why, google for "most vexing parse"). If your compiler supports enough C++11, use braces, not parentheses, to avoid such errors when initializing objects, or give c and t correct types so that you could write ChessPiece cp(c, t);
because I used the operator = i
you didn't use operator=, you used copy initialization, which is another form of initialization that is immune to MVP