DEV Community

dinhluanbmt
dinhluanbmt

Posted on

C++, Forward declaration

Forward declaration is a powerful technique that allows us to declare a type without needing its full definition. This reduces the number of dependencies and can improve compilation times. It is particularly useful in large projects or library development.

Ex: class A header file (A.h)

// we don't need to include the header file B.h here
// #include "B.h" in A.cpp  to instantiate B object
class B;// forward declaration 
class A {
private:
    B* pB;// ok
    B& rB;// ok
    //B ob;// error because compiler need to know the definition of class B
public:
    void method() {
        //pB->dosomething(); error        
    }
    void use_classB_method();

};
Enter fullscreen mode Exit fullscreen mode

Class A definition (A.cpp)

#include "B.h"
void A::use_classB_method() {
    pB = new B();
    pB->dosomething();
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)