Is forward declaring a class a correct way to hide the implementation?

Viewed 29

In order to create an static library for MyClass I have this small example:

// MyClass.h

class Obj;
class MyClass {
public:
    MyClass();
    ~MyClass();
    void doSomething();
private:
    Obj* obj = nullptr;
};


// MyClass.cpp
#include "MyClass.h"
#include "Obj.h"

MyClass::MyClass() : obj(new Obj()) {}
MyClass::~MyClass() { delete obj; }

void MyClass::doSomething() {
    std::cout << "Hello from MyClass!" << std::endl;
    obj->sayHello();
}

Assuming the header Obj.h is really heavy, may I just forward declare Obj in the header of MyClass such that when exporting the library I will only need to share with other users the MyClass.h and MyClass.lib files ?

I tested the code and everything works correctly. My question more specifically is; is this a good practice or are there any other better alternatives ?

Thanks !

0 Answers
Related