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)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay