Darkgamma
Darkgamma

Reputation: 123

Object does not name a type?

I have a chunk of code that keeps failing on me no matter how much I thin it down. The code in question is:

#include <iostream>
class Tile;
class Tile{
    public:
    void PRINTME();
};

void Tile::PRINTME() { std::cout << "Blergh"; }

Tile Wall;
Wall.PRINTME();

It displays the following error message:

(...)\MapTiles.h|11|error: 'Wall' does not name a type|

I might be relatively new to C++ programming, but a couple of hours of digging around Stackexchange and tutorials on classes tells me that the above snippet should run.

Multiple other such problems here have been solved using forward declarations, but in this case it is trying to read the object "Wall" as a class. As the class was previously quite a bit larger, I trimmed it considerably yet it still fails to work decently. I based this example off the Tutorialspoint tutorial on C++ classes and member functions.

I'm using MinGw that comes with Code::Blocks 13.12, on a Windows 7 (64bit) machine with the compiler flag -std=c++11 ticked.

Upvotes: 1

Views: 1257

Answers (1)

danielschemmel
danielschemmel

Reputation: 11126

You are trying to execute a statement (a function call to be explicit) outside any function. This doesn't work.

#include <iostream>
class Tile;
class Tile{
    public:
    void PRINTME() { ::std::cout << "I PRINTED MESELF!\n"; }
};

int main()
{
    Tile Wall;
    Wall.PRINTME();
}

Putting it someplace where statments are allowed it works.

As to your guess about forward references, they are completely unnecessary for your code to work - in fact you need not even name the class Tile at all:

#include <iostream>
struct { void PRINTME() { std::cout << "I PRINTED MESELF!\n"; } } Wall;
int main() { Wall.PRINTME(); }

Upvotes: 7

Related Questions