Hiding the implementation of an inner class using a namespace

I am developing a library and would like to provide my users with an open interface, different from the real implementation, which is hidden in the namespace. That way, I could only change the HiddenQueue class without changing myQueue, which would be available only to users.

If I put the C ++ HiddenQueue code in myQueue.cpp, the compiler complains that _innerQueue is of an incomplete type. I thought the linker was able to resolve this. What am I doing wrong here?

// myQueue.h namespace inner{ class HiddenQueue; }; class myQueue{ public: myQueue(); ); private: inner::HiddenQueue _innerQueue; }; /////////////////////////// // myQueue.cpp namespace inner{ class HiddenQueue{}; }; 
+4
source share
3 answers

The compiler must know the exact layout of the object by looking at the header file in which it is defined.

Your code says that the MyQueue class has a member of type InnerQueue , which will be part of the memory layout of MyQueue objects. Therefore, to display the MyQueue memory MyQueue he needs to know the InnerQueue memory InnerQueue . That this is not so because you say "well, it is defined elsewhere."

What you are trying to do is closely related to the " PIMPL idiom " / "firewall compiler".

To solve the problem, you must either include HiddenQueue.h in your header or declare _innerqueue as a pointer:

 class myQueue { public: myQueue(); private: inner::HiddenQueue* _pinnerQueue; }; 

Using a pointer is possible because the pointer has a known memory size (depending on your target architecture), so the compiler does not need to see the full HiddenQueue .

+6
source

To be able to make a member of a class, for this you need to have a definition, not just a declaration. (A declaration is sufficient for a pointer or reference to a class).

+1
source

You need to point to the _innetQueue, not the object itself:

 std::auto_ptr<inner::HiddenQueue> _innerQueue; 

Pimpl ideom or d-pointer search form

+1
source

Source: https://habr.com/ru/post/1309417/


All Articles