r/cpp • • 27d ago

How I design C++ classes

https://rafb.eu/blog/cpp-class-design/

This is my first ever blog-post, any feedback is welcome! ofc, no AI got used.

69 Upvotes

46 comments sorted by

View all comments

Show parent comment

1

u/victor-s8n 23d ago

You would still expose internal dependencies and logic to the public interface. Which then gets pulled in into all other files including the header.
Yes, your are correct, but the bigger compile-time and leaking of internal information still occurs.

1

u/LongestNamesPossible 23d ago

Why would that have to be true?

Whatever data structures are being used to communicate are going to be in the header part of the compilation unit that contains boost asio, but if the data structures are lightweight then the dependency is lightweight.

1

u/victor-s8n 23d ago

Let's go with `#include <regex>`. If you include it in your header, because you want it as a member-variable, all other #includes of that header will include `<regex>`. Although <regex> is only used internally inside the class. <regex> is known to compile slow.
If you now create a class to hide regex for a specific use-case, you get a pimpl or my approach.

2

u/LongestNamesPossible 23d ago

If you make a function that takes a string and returns a string, the regex can be included only in the compilation unit for that function.

It doesn't need to be in the header to use the function because it can be hidden in the implementation. Then the compilation time is isolated to a single compilation unit.

1

u/victor-s8n 23d ago

Sure, but then you got to `include <functional>`.

Another perspective: Feels like a variant of information-hiding, a variant of pimpl/my-approach.

Doesn't it?

1

u/LongestNamesPossible 23d ago edited 22d ago

Sure, but then you got to include <functional>.

What does that have to do with anything? Why would you have to include that?

a variant of pimpl/my-approach. Doesn't it?

The difference is that if you wrap something in regular functions you are just calling into functions like any other normal function you link in. If you have a structure where you are allocating memory and dereferencing a pointer you have unnecessary indirection.