Search code examples
c++inheritanceforward-declaration

Forward declaration of class variable


Can i forward declare class variable in other class to avoid circular dependency and if yes, how? Example:

//another file
class Engine;
extern vector<Block*> Engine::MapBlocks;

//Engine.h
class Engine
{
public:
   vector<Block*> MapBlocks;
};

Its possible?


Solution

  • No, what you're trying to do is not possible. It is not possible to declare non-static class members outside the class definition. If such a thing was allowed, it would allow any code to arbitrarily modify any class (e.g. by declaring a member that is not actually part of the class). Logically, that breaks the intent of using classes (e.g. encapsulation) totally.

    However, it is possible to pass and store pointers to a class type, without the definition being visible. In this case

    #include <vector>     // necessary for use of std::vector
    
    class Block;
    
    class Engine
    {
       public:
         std::vector<Block*> MapBlocks;
    
          // preferably declare constructors and/or other member functions
          //    that initialise MapBlocks appropriately to needs
    };
    

    This will work because the compiler does not need to have visibility of the definition of Block to store pointers in a container.

    Naturally, any code which attempts to instantiate a Block (e.g. some_engine.MapBlocks.push_back(new Block)) or call its member functions (e.g. some_engine.MapBlocks[some_valid_index]->some_member_function()) relies on visibility of a definition of class Block, not just a forward declaration.