0

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 !

Ediolot
  • 501
  • 2
  • 6
  • 19
  • [pImpl idiom](https://en.cppreference.com/w/cpp/language/pimpl) – Nelfeal Sep 23 '22 at 12:34
  • @Nelfeal I guess you can interpret pimpl in a broader way. But as far as I know in the classic pImpl the same interface provided by public class is "duplicated" by the private one (and the public method forwards the call to the private one). I think this question is more general. E.g. you could have several private classes that you use for your implementation and you can forward declare them all. IMHO it is a good patern. – wohlstad Sep 23 '22 at 12:37
  • One alternative would be to use `void* obj` instead, then forward declaration will not be required (but some adaptations in the actual implementation WILL be). –  Sep 23 '22 at 12:38
  • 1
    @bbbbbbbbb using `void*` in c++ is usually discouraged, as it causes you to loose type safety. – wohlstad Sep 23 '22 at 12:41
  • 1
    @wohlstad I've seen this kind of thing done where the public class doesn't exactly duplicate the hidden implementation, and people would call it pImpl. Even if you have multiple private classes, don't they constitute the *implementation* of the public class? – Nelfeal Sep 23 '22 at 12:45
  • @Nelfeal I agree it can fit this more general case. It's just that whenever I encountered using this term (pImpl) it was usually in the more strict/limited sense that I menioned. BTW the bridge design pattern is related and is usually implemented using pImpl (https://en.wikipedia.org/wiki/Bridge_pattern). – wohlstad Sep 23 '22 at 12:50

0 Answers0