Doubt Class C++

Asked

Viewed 87 times

6

I would like to understand why some classes in C++ have the following statement:

class Bla;

class Ble
{
 ....
}

My doubt is about the Bla class, it has no meaning as far as I could see.

  • It really is meaningless, I would need more context and indicate better what you want to know. Maybe you don’t know anything about it, but some indication needs to be given. Ttalvez putting a real code where it has it helps.

  • Let me get an example code

  • Here is an example: https://github.com/pocoproject/poco/blob/dcdcee5afab6e8972f1b144ef7e884f85e83a3/Net/include/Poco/HTTPStream.h#L35

1 answer

7

This is called forward declaration. It is necessary to allow cyclic references between classes. So it is possible to make the class Ble have a pointer to a class object Bla and then do the class Bla have a pointer to a class object Ble:

class Bla;

class Ble
{
    Bla *bla;
};

class Bla
{
    Ble *ble;
};

The first line serves to declare that there will be a class called Bla, but without yet defining its content. This makes it possible to declare pointers and references to objects in this class. At a later time it is necessary to define the content of the class.

In addition to solving the problem of cyclic references, this also avoids the need to give #include to obtain the definition of classes when only pointers or references are to be created. In this case, for example, instead of giving #include "bla.h" it is possible to just do forward declaration class Bla. Doing this can make the build process a little faster.

  • Really, it makes sense! Very well explained, thank you for the answer! because this question left me very curious!

  • Again, thanks for adding the correct term, I will be able to search for more details!

  • So come on, I declared the Ble class and it has as reference Bla, if I make the forward declaration I will not need to define the content of the Bla class before the Ble class?

  • A little confused to understand without seeing the code. But in practice what this allows is to say that a class will exist, but without indicating its content. You can declare a pointer of a class declared as such, but you cannot create objects.

  • Let me give you an example https://github.com/pocoproject/poco/blob/dcdcee5afab6e8972f1b144ef7e884f85e83a3/Net/include/Poco/HTTPStream.h#L35

Browser other questions tagged

You are not signed in. Login or sign up in order to post.