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)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay