class foo; in header file

后端 未结 9 2006
执笔经年
执笔经年 2021-01-20 08:36

Is some one able to explain why header files have something like this?

class foo; // This here?
class bar
{
   bar();

};

Do you need an in

相关标签:
9条回答
  • 2021-01-20 09:04

    That's a forward declaration. Consider the following example:

    class foo; // you likely need this for the code beneath to compile
    class bar {
        void smth( foo& );
    };
    

    If you haven't included the definition of class foo in such a way that the compiler sees it before compiling the definition of class bar the code will not compile (the compiler will say it doesn't know what foo means) unless you have the forward declaration.

    0 讨论(0)
  • 2021-01-20 09:05

    Just curious, why do we need the term forward declaration at all? Isn't a forward declaration simply a declaration (as opposed to a definition)?

    class X;  // declaration
    
    class X   // definition
    {
        int member;
        void function();
    };
    
    0 讨论(0)
  • 2021-01-20 09:10

    That's a forward declaration. You need it for example if class bar has a pointer to a foo object, but you don't want to include the whole definition of the foo object immediately.

    0 讨论(0)
提交回复
热议问题