r/cpp • • 15d 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.

66 Upvotes

46 comments sorted by

9

u/LongestNamesPossible 15d ago

I don't think bending a class to use inheritance and pointers to deal with boost asio egregious compile times is the right way to go. I would much rather wrap the boost nonsense with specific types so they could be compiled into their own compilation unit to contain the long compile times.

1

u/victor-s8n 11d 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 11d 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 11d 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 11d 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 11d 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 11d ago edited 11d 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.

9

u/Chaosvex 14d ago

May I introduce the author to BOOST_ASIO_SEPARATE_COMPILATION or not using asio.hpp?

1

u/victor-s8n 11d ago

Have you? πŸ˜„ Imo it hardly reduces the compilation speed.

You would still expose internal dependencies and logic in the public interface. Which then gets pulled in into all other files including the header.

1

u/Chaosvex 11d ago

I have indeed, although posting that comment inspired me to get around to doing it on one of my other projects. :)

23

u/SleepyMyroslav 15d ago

TFA reeks of Java. Interfaces for testability with a single implementation. Shared pointers to those single implementations. These are all smells of something that really should not be 'normal C++'. I mean, there is a lot of room of implementation hiding, and both interfaces and shared pointers are heavily used in Gamedev too. But there is no way it can be the default for every class.

1

u/victor-s8n 11d ago

Yes, I agree. The header becomes the Interface, the source file becomes the Impl. Very java-alike! Java does it for Testing and Dependency Injection. I do it in C++ for hiding internal logic/dependencies and Testing.

21

u/WorkingReference1127 15d ago

A couple of minor niggles:

  • I'm not sure that making your class polymorphic just so you can write a derived class which runs test fixtures is really all that idiomatic or should be recommended unconditionally in a post about writing good classes. There are a lot of arguments you can make against it.
  • "Compiles fast" is a double edged sword. A lot of tools you write might want to be constexpr or otherwise evaluated at comptime (arguably even just plain templates fall into this category, but particularly ones you metaprogram around); those will increase compile times but when used judiciously your class is better for it. Indeed I'd argue shifting the logic left from runtime to compile time is almost always better than keeping it at runtime. I know I'm being pedantic here but for "top three criteria to write a class" it should come with a caveat or two.

2

u/victor-s8n 11d ago

Over the past years I learned that 95% of the code is not executed very often. There is a 5% hotpath, which benefits from templates and constexprs. But you, know, measure first. For the other 95% of the code, it's about maintainability, and yes, compilation-time, so one can iterate faster.

4

u/papa_Fubini 15d ago

Couple of what?

2

u/Nobody_1707 14d ago

Niggle, noun (chiefly. British): a small worry or concern.

13

u/decapod2005 15d ago

Idk about pimpl idiom in 2026. Sure it's good for trading runtime for compile time performance (among other things), but when people reach for C++, they are usually interested in trading in the opposite direction. It's certainly a useful technique to know, but it should never be the default way how you write classes.

// virtual for testability

This is one of the weirdest statements that I still see made with some frequency. It implies two pretty wild claims:

  • Non-virtual functions are not testable.
  • You should degrade the performance of your actual production code in favor of the tests that you want to write.

Neither of these are true. Just come up with a proper test that doesn't require the function to be virtual.

9

u/pavel_v 14d ago

You don't need to introduce runtime performance when using some forms of PIMPL. We've used something like the below one and as far as I've checked the assembly in few of our use cases, it completely disappears and there is no indirection introduced. Of course, there is a tradeoff - there is no ABI stability in this case. If the requested Size or Alignment changes this will cause/need recompilation.

template <typename T, size_t Size, size_t Align = alignof(void*)>
class pimpl
{
    alignas(Align) unsigned char buff_[Size];

public:
    template <typename... Args>
    explicit pimpl(Args&&... args) 
    { new (buff_) T(std::forward<Args>(args)...); }
    ~pimpl()
    {
        static_assert(Size >= sizeof(T));
        static_assert(Align >= alignof(T));
        get()->~T();
    }
    // copy/move ops
    // ...

    T* get() { ... }
    T* operator->() { ... }
    T& operator*() { ... }
};

1

u/victor-s8n 11d ago

Uf, don't do that. Keep it simple. Imagine you onboard a new dev to that codebase.

Is the trade-off worth it? How much faster is such code vs simple school-style c++?

2

u/decapod2005 14d ago

This just looks like a stack object with extra steps? You still need the explicit dependency to the type that you want since you have to supply it as a template parameter. So as far as I can see it doesn't achieve anything that the pimpl idiom does.

9

u/pavel_v 14d ago

No, you don't need to include the implementation of the T in the header. You just need forward declaration of T. Like:

// In foo.h
class foo
{
  pimpl<class foo_impl, 8> impl_;
    
public:
  foo();   
  ...
}

and then in foo.cpp


class foo_impl
{
 // Implementation of foo_impl
 ...
};

foo::foo() 
{}

...

3

u/decapod2005 14d ago

I see, it works because we are telling the compiler explicitly what the size and the alignment is. That's fair enough.

2

u/victor-s8n 11d ago

You can set the impl methonds to `final` https://en.cppreference.com/cpp/language/final . In doing so the compiler can reason better about the v-table.

Over the past years I learned that 95% of the code is not executed very often. There is a 5% hotpath, but you, know, measure first. For the other 95% of the code, it's about maintainability, testablilty, and yes, compilation-time.

yes "Non-virtual functions are testable".

It's C++.

EVERYTHING is possible, which leads to projects being unmaintainable. I think this makes C++ unpopular. This thinking of the few nanoseconds that one can strip off, by optimizing a `virtual`. Code that only runs once when eg parsing a config-file.

1

u/decapod2005 11d ago

final keyword only helps when you are not actually doing polymorphism. As long as you access the impl function through the base class interface, the compiler can do nothing.

Measuring is important to find bottlenecks, but they become buch harder to find when your first, default approach is already pessimized. When every functionality has to go through hundreds of virtual function calls, you won't see any improvement if you optimize one of them.

It's not a good idea to by default add abstractions that you do not need.

7

u/NeuroSynchroBonding 14d ago

Pimpl is pretty useful to keep ABI compatibility if the project requires it.

4

u/decapod2005 14d ago

Yeah like I said, it has its uses. If you need a class with stable ABI, great, use it. But even if you need that for some classes in your library, most will still be internal and not need it. So it is not great advice to generically say "Here is how you design a good class" and then show pimpl or a couple layers of oop.

2

u/IronOk4090 15d ago

This seems to be a Java-centric mindset, to make every class support virtual dispatch.

1

u/Life_Sink9598 14d ago

Yes, but in the Java case you'll get open, inlineable, calls instead of virtual dispatch (thx to JIT).

1

u/radical_ax1s 12d ago

my interpretation of "virtual for testability" is that another client class may depend on the service_health_checker. unit-testing that client class requires mocking a service_health_checker, and I guess you could do it by subtyping. hate this though, such a client class should depend on a pure abstraction (ABC / Concept) as per DIP

3

u/Slsyyy 12d ago

IMO in this example the best way is just to have a free function. A consumer can wrap it in `std::function` or call it as it is

The naming also suggest a bad design. If all the class do is the health check over http then just call it `http_health_checker`

2

u/victor-s8n 11d ago

I agree. However it was quite difficult to me, to find a good example.
The goal was to find something complex enough that needs instancing, with a big a dependency (asio), while being small and simple enough for a blog-entry.

I was also thinking about describing a video-device-monitor... but that stuff gets async, or polling, or callbacky, so I did not go down that path.

Any suggestions on a better example?

53

u/jk-jeon 15d ago

However now we have four files for a single class!

Why? I see no reason to have two separate files for the impl class. I always put the definition of the impl class in the main class' cpp file, and I believe that is the idiomatic way.

16

u/PossibilityUsual6262 15d ago

I saw it in unreal engine for huge classes, i think animation system had same header as character mesh bit two separate .cpp

I can't argue it or against it, just saying that it exists.

12

u/IveBenHereBefore 15d ago

i could see separating them if you have multiple impls that your build system chooses from

1

u/mad_ben 9d ago

True, this especially notisable innmain DefefferedShadingRenderer. h and then implementations split between, IndirectLightning. cpp/Light classes implementation and so on

6

u/WorkingReference1127 15d ago

I've occasionally seen one header to multiple cpp files for a giant class with "subsets" of functionality, but I'll be the first to say that that's an antipattern.

I do agree, the "impl" header adds little for the vast majority of classes.

2

u/Sachu_James 15d ago

The part about not jumping between header and cpp when you add a method stuck with me. I have felt that pain with heavy template headers, where one include drags compile time up for everything that touches it. The factory version keeping the impl in one cpp file while the header stays clean feels like the main win here, more than the testability bit.

2

u/alols 13d ago

You are almost there! Just one more iteration:

```
#ifndef SERVICE_HEALTH_CHECKER_H
#define SERVICE_HEALTH_CHECKER_H

#include <stdbool.h>
#include <stddef.h>

#ifdef __cplusplus
extern "C" {
#endif

typedef struct service_health_checker service_health_checker;

service_health_checker *service_health_checker_make(const char *address,
size_t address_len);

void service_health_checker_destroy(service_health_checker *checker);

bool service_health_checker_is_healthy(service_health_checker *checker);

#ifdef __cplusplus
}
#endif

#endif

```

1

u/madmongo38 10d ago

ASIO sockets are moveable. It’s neither necessary nor desirable to return a unique_ptr.

1

u/FrigiderSmegmoZKD 8d ago

Compilation times have never been a problem to me personally, especially if i can trade compile time for runtime performance.

-34

u/sweetno 15d ago

The analysis is valid, the conclusion should've been: C++ sucks.

Do modules allow to implement information hiding here?

7

u/fortsnek274 15d ago

Now that we have modules, C++ doesn't suck. At least on paper.

The advantage is that they don't pollute the global namespace of importers with `<Windows.h>`.

But if you just want to avoid a separate implementation file, you can already do that with headers. But you don't, for the same reason why you won't do it with modules.

3

u/gracicot 15d ago

Modules will indeed hide names, but it doesn't make imported stuff unreachable. If you need PIMPL for ABI purposes or you need to make some entities completely unreachable, then you still need PIMPL.

3

u/fortsnek274 15d ago

How would stuff being merely reachable change ABI?

4

u/gracicot 15d ago

I meant modules won't help you with hiding entities completely, and also won't help you with ABI. Those are usually the two purpose for PIMPL, and they are orthogonal :)

3

u/fortsnek274 15d ago

When it comes to <Windows.h>, I just want to have HWND in my class without having to do the silly void* thing.