(object) does not name a type. Whats going on?

I think the code shows the problem best

class blok
{ public:
    sf::RectangleShape TenBlok;
    int x,y;
    blok(int posX ,int posY)
 {
     x = posX;
     y = posY;
 }
 void place(int x,int y)
 {
        TenBlok.setPosition((float)x,(float)y)
 }
};

[...]

class Trawa : public blok
{

int id = 0;
sf::Texture tekstura;
tekstura.loadFromFile("trawa.png"); //<---- here it says "tekstura does not name a type"
TenBlok.setTexture(tekstura); //<---- here it says "TenBlok does not name a type"

};

Error says that the object doesnt name a type, but oddly enough CodeBlocks sees bother tekstura and TenBlok as vaild objects becouse id hints functions those objects contain

1 answer

  • answered 2019-07-10 22:16 R Sahu

    You cannot use statements

    tekstura.loadFromFile("trawa.png"); //<---- here it says "tekstura does not name a type"
    TenBlok.setTexture(tekstura); //<---- here it says "TenBlok does not name a type"
    

    in the class definition. They are not declarations. You can have such statements inside the definition of a member function, but not the class itself.

    A simpler class that will fail with similar errors:

    struct Foo
    {
       int i;
       i = 10;
    };
    

    To initialize i (or execute similar statements), use a constructor.

    struct Foo
    {
       int i;
       Foo() { i = 10; }  // For demonstration. It will be better to initialize
                          // i using Foo() : i(10) {}
    };
    

    For you class, you probably need:

    class Trawa : public blok
    {
       int id = 0;
       sf::Texture tekstura;
    
       Trawa() : blok(0, 0)  // Assume position to be (0, 0)
       {
          tekstura.loadFromFile("trawa.png");
          TenBlok.setTexture(tekstura);
       }
    };