c++oopfriend-class

C++ friend class invalid use of incomplete type OOP


I have decided learn some OOP and I started get rid of conditionals (I know in this program this in unnecessary but I have to start with simply example).

In class DirectConditions, I have my conditions and I would pass object of SnakeGame by reference to friend class DirectConditions's method and change value of some variables of SnakeGame in DirectConditions's method.

Error:

invalid use of incomplite type 'class DirectConditions::SnakeGame' snakeObj.snake[0].xCoor+=1;

Another Question:

May I take this occasion to ask: this way to get rid of conditionals(if's) is good? I would really appreciate help.

Providing the code:

snakeGame.hpp:

#ifndef _SNAKEGAME_HPP
#define _SNAKEGAME_HPP
#include<string>
#include"directConditions.hpp"
#include<map>

class SnakeGame{
    public:
        SnakeGame();
        void mainLogic();
        void check();

        friend class DirectConditions;

    private:
        const int width,height;
        int sizeOfSnake;
        std::string direction;
        std::map<std::string,DirectConditions*> directMap;


        struct Snake{ int xCoor,yCoor; }snake[100];
        enum Directions{up,down,left,right} directEnum;
        void initializeMap();
};
SnakeGame::SnakeGame():width(500),height(500),sizeOfSnake(3){}

void SnakeGame::check(){
    for(int i=sizeOfSnake;i>0;--i){
        snake[i].xCoor=snake[i-1].xCoor;
        snake[i].yCoor=snake[i-1].yCoor;
    }
    directMap[direction].goToDirection(this);
}
//private fun
    void SnakeGame::initializeMap(){
        directMap["right"]=new GoRight;
        directMap["left"]=new GoLeft;
        directMap["up"]=new GoUp;
        directMap["down"]=new GoDown;
    }


#endif 

directConditions.hpp:

#ifndef _DIRECTCONDITIONALS_HPP
#define _DIRECTCONDITIONALS_HPP
#include"snakeGame.hpp"

class DirectConditions{
    public:
        class SnakeGame;
        virtual void goToDirection(SnakeGame&)=0;
        virtual ~DirectConditions(){};
};

class GoRight:public DirectConditions{
    public:
        void goToDirection(SnakeGame& snakeObj){
            snakeObj.snake[0].xCoor+=1;
        }
};

class GoLeft:public DirectConditions{
    public:
        void goToDirection(SnakeGame& snakeObj){
            snakeObj.snake[0].xCoor-=1;
        }
};

class GoUp:public DirectConditions{
    public:
        void goToDirection(SnakeGame& snakeObj){
            snakeObj.snake[0].yCoor+=1;
        }
};

class GoDown:public DirectConditions{
    public:
        void goToDirection(SnakeGame& snakeObj){
            snakeObj.snake[0].yCoor-=1;
        }
};

#endif

Solution

  • You should avoid including of headers by each other - that's why you're getting "invalid use of incomplete type". Change those includes to forward declarations and move implementation of methods to cpp files.