Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why don't methods defined in classes in C++ need forward declarations when referring to methods that only show up later in the class?

Why is this a compilation error:

void f() {
    g();
}

void g() {

}

but not this:

class X {
    void a() {
        b();
    }

    void b() {
        
    }
};

I was under the assumption the compiler would (at least, generally) read code from top-down, left-to-right, and that was the reason that in the 1st piece of code we'd need to define a void g() forward declaration before f() to make the code compile. But that logic doesn't seem to apply to classes -- why?

like image 275
devoured elysium Avatar asked Dec 28 '21 12:12

devoured elysium


People also ask

Why does C need forward declaration?

In some object-oriented languages like C++ and Objective-C, it is sometimes necessary to forward-declare classes. This is done in situations when it is necessary to know that the name of the class is a type, but where it is unnecessary to know the structure.

What is the purpose of forward class declaration?

A forward declaration tells the compiler about the existence of an entity before actually defining the entity. Forward declarations can also be used with other entity in C++, such as functions, variables and user-defined types.

Why use forward declaration instead of include?

A forward declaration is much faster to parse than a whole header file that itself may include even more header files. Also, if you change something in the header file for class B, everything including that header will have to be recompiled.

When can I use forward declaration?

You will usually want to use forward declaration in a classes header file when you want to use the other type (class) as a member of the class. You can not use the forward-declared classes methods in the header file because C++ does not know the definition of that class at that point yet.


1 Answers

C dates from 1972; C++ dates from 1985. C++ inherited the forward declaration requirement and the design of header files from C, and kept that behavior for compatibility, but was able to improve things for classes, with C didn't have.

like image 89
Boann Avatar answered Nov 15 '22 08:11

Boann