C++ encapsulation

Started by
4 comments, last by Ravyne 11 years, 3 months ago

Hi !

I've been philosophizing about where to draw the line when it comes to encapsulation. It seems to me that when a class needs to contain data types that would preferably be forward declared in the header file, it would be most beneficial to just forward declare one structure to hold all of its member variables.

The way I see it, this first of all reduces the number of dynamic allocations needed to just one. It reduces the amount of redundant information visible through the class interface and nearly eliminates the need to recompile any file that is dependent of the class.

Does this seem like sound design? I'm curious to know why it is not a more common practice.

- Dave

Advertisement
It seems to me that when a class needs to contain data types that would preferably be forward declared in the header file, it would be most beneficial to just forward declare one structure to hold all of its member variables.

[...]

Does this seem like sound design? I'm curious to know why it is not a more common practice.

It's actually quite common. It even has a bunch of names: the "pimpl idiom", the "compiler firewall idiom", the "cheshire cat idiom" and the "bridge pattern".

Ninja'd by edd. But here's a link to Wikipedia.

Ah, I never considered the similarity to that technique. Cool, then there's some established justice to complicate things a little :)

You may also want to peek at how that can relate to the flyweight pattern. :)
void hurrrrrrrr() {__asm sub [ebp+4],5;}

There are ten kinds of people in this world: those who understand binary and those who don't.

Keep in mind, however, that just because this pattern has some nice properties, it doesn't mean that this level of abstraction is necessarily appropriate or even desirable all the time. You need to consider how the class is to be used, its scope of responsibility, how stable its api is, and other things. For example, this wouldn't be appropriate for a 3D vector or matrix class, but might be appropriate for, say, a 3D renderer.

throw table_exception("(? ???)? ? ???");

This topic is closed to new replies.

Advertisement