Class foo; in the header file

Can anyone explain why the header files have something like this?

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

};

Do you need an include statement when using this?

Thank.

+3
source share
9 answers

The first class foo;is called forward declaration of class foo. It just lets the compiler know that it exists and what it calls the class. This makes foo what is called an "incomplete type" (if the full declaration of foo has not already been noticed). With an incomplete type, you can declare pointers of this type, but you cannot select instances of this type or do anything that requires knowing its size or members.

, , , . , ++ ; Java , Java . , , ; , , , (.. ), , , .

, , , , , ; , , , , .

+10

. , , bar foo, foo.

+2

. , .

in foo.h
--------
#include "bar.h"

class foo
{
public:
    foo(bar *bar);
private:
    foo *m_foo;
};

and in bar.h
------------
class foo;
class bar
{
public:
    void methodFooWillCall();
protected:
    std::list<foo *> myFoos;
}
+1

, ? ( )?

class X;  // declaration

class X   // definition
{
    int member;
    void function();
};
+1

. :

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

class foo , class bar, ( , , foo ), .

0

'foo'. , (, ), ! (class foo { ... };).

, , , .

0

. foo . , . Bar Foo .

class Bar
{
   Foo * foo;
};
class Foo
{
   Bar * bar;
};

, Bar foo . , , foo. , class Foo Bar ( , main ).

class Foo; //Tells the compiler that there is a class Foo coming down the line.
class Bar
{
   Foo * foo;
};
class Foo
{
   Bar * bar;
};
0

. , , foo . , , .

. , ,

//a.h
#include "b.h"

class A
{
    void useB(B obj);
}

// b.h
#include "a.h"
class B
{
     void useA(A obj);
}

, a.h b.h, a.h, . , :

//a.h
class B;

class A
{
    void useB(B obj);
}

// b.h
class A;

class B
{
     void useA(A obj);
}

: , , /. , , , .

0

:

file bar.h:

        #include "bar.h"

        class Foo
        {
        Bar* bar_ptr;
        }

file foo.h:

        #include "foo.h"

        class Bar
        {
            Foo* foo_ptr;
        }

, - #include, , , Foo , Bar, Bar , Foo.

:

        class Bar;

        class Foo
        {
        Bar* bar_ptr;
        };

file foo.h:

        class Foo;

        class Bar
        {
            Foo* foo_ptr;
        };
0
source

Source: https://habr.com/ru/post/1743150/


All Articles