Sign in to follow this  
Vanderry

C++ encapsulation

Recommended Posts

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

Share this post


Link to post
Share on other sites
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".

Share this post


Link to post
Share on other sites

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.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this