Friends, Abstract classes and Factory pattern - c++

Good day to you all...
I'm working on a complex project on my company which I use some wringled Factory Design pattern in the project. Omiting the details; I have some classes (I call them "Devices") which can only be created by "Readers":
class DeviceBase // this is a virtual base class
{
public:
//some stuff
friend class ReaderBase; // this is OK and necessary I guess?
private:
DeviceBase(); // cannot create a device directly
//some more stuff
}
class Device1: public DeviceBase // some extended device
{
public:
//some stuff
private:
//some more stuff
}
class Device2: public DeviceBase // some other extended device
{
public:
//some stuff
private:
//some more stuff
}
Now the "Reader", which happens to be factory for devices:
class ReaderBase
{
private:
DeviceBase[] _devices; // to keep track of devices currently "latched"
public:
// some other methods, getters-setters etc ...
// this method will create the "Devices" :
virtual bool PollforDevice ( DeviceType, timeout) = 0;
}
Now, this is my factory class; but it's (as you can see) pure virtual. I have special Readers inherit from this one:
class InternalReader: public ReaderBase
{
public:
// define other inherited methods by specifics of this reader
bool PollforDevice( DeviceType dt, timeout ms)
{
switch(dt)
{
case Device1: { /* create new device1 and attach to this reader */ } break;
case Device2: { /* create new device2 and attach to this reader */ } break;
}
// show goes on and on...
}
}
class ExternalReader: public Reader
{
public:
// define other inherited methods by specifics of this reader
bool PollforDevice( DeviceType dt, timeout ms)
{
switch(dt)
{
case Device1: { /* create new device1 and attach to this reader */ } break;
case Device2: { /* create new device2 and attach to this reader */ } break;
}
// show goes on and on...
}
}
The reason I use this pattern is: I'm writing for a system that can have multiple of these "readers" attached at the same time and I must use them all at the same time.
And these "Devices": I can make theirs constructor public too, and everyone would be happy; but I want to make sure that they are not created by the code writers themselves (to make sure other coders of it)
Now the questions:
Should I explicitly declare in every "Device" that ReaderBase is a friend? Or just declaring at the base "DeviceBase" should be enough?
Should I explicitly put in every "Device" that the "Readers" inherited from the "ReaderBase" are also friends of these devices, or just putting ReaderBase is enough?
Instead of making whole "ReaderBase" class a friend, can I (and should I) just make the member method "PollforDevice" a friend? Knowing that it's a pure virtual method, would that make inherited copies friends as well?
I'm sorry that the question is a very long one, but I just want to make it clear.
Thanks in advance...

Why bother about constructability of pure abstract base classes like DeviceBase? It can't be constructed anyway if it is a properly designed contract or abstract base class. Unless you have to fit into some kind of framework which you didn't mention, just do the opposite of hiding, e.g.:
struct DeviceBase {
virtual void Foo() = 0;
virtual void Bar() = 0;
virtual ~DeviceBase() = default;
};
By the way, declaring the constructors or destructors private will very effectively make your class "sealed". If for some reason DeviceBase is not abstract (which were a serious design flaw in my eyes) make constructors protected not private. Where you need to bother, is the constructor accessibility of the concrete Device classes. Assuming that you are going to "publish" these implementation classes (i.e. their definitions are accessible to users of your library) and you wish to stress that direct construction is prohibited, use the "access idiom" (my invented name for this):
namespace impl_detail {
class DeviceAccess;
}
class ConcreteDevice1 : public DeviceBase {
friend class impl_detail::DeviceAccess;
// implementation of DeviceBase and all other stuff go
// into the "private" section
};
namespace impl_detail {
class DeviceAccess {
template< class TDevice >
static DeviceBase* Create()
{
return new TDevice;
}
};
};
In your Reader classes use impl_detail::DeviceAccess::Create to construct Device instances, e.g.:
// Your ExternalReader::PollForDevice...
switch (dt) {
case Device1:
return impl_detail::DeviceAccess::Create<ConcreteDevice1>();
case Device2:
// etc...
}
Long story short, best solution is to not publish concrete implementation classes at all, second best some kind of "psychological barrier" which restricts construction, e.g. of the above kind...

Should I explicitly declare in every "Device" that ReaderBase is a friend? Or just declaring at the base "DeviceBase" should be enough?
Should I explicitly put in every "Device" that the "Readers" inherited from the "ReaderBase" are also friends of these devices, or just putting ReaderBase is enough?
As friendship is not inherited (at either side of the friendship relation), the only way your scheme will work is when you declare friendship of every derived Reader in every derived Device. This creates a tight coupling between the Reader classes and the Device classes that is not a nice design.
3) Instead of making whole "ReaderBase" class a friend, can I (and should I) just make the member method "PollforDevice" a friend? Knowing that it's a pure virtual method, would that make inherited copies friends as well?
You could make ReaderX::PollforDevice a friend instead of the entire ReaderX class, but it won't help you much and only opens the door for hard to resolve circular dependencies.
Actually, it is quite hard to create a design where classes of hierarchy X can only be created by classes of hierarchy Y and no one else, without creating a tight coupling between the classes in both hierarchies.
My approach would be
First and foremost, educate your coworkers that if they want a DeviceX, then they can obtain it from a ReaderY and in no other way. Make sure this is enforced in code reviews.
All the other steps are just damage control.
Make sure only the BaseDevice class gets exposed to code outside the Reader's implementation.
Make the destructor of all Device classes protected. This ensures that Device classes can only be cleaned up by derived classes or friends (and automatically rules out stack allocation by non-friends). Should get someone to think twice if they accidentally try to use a Device class directly.
Make the ReaderBase a friend of DeviceBase and give ReaderBase a function to do the actual cleanup of a Device. This is needed to ensure Devices can be cleaned up.

Related

Fix a large class using inheritance

It seems to me that my class is too big and complicated, I would like to reduce it. Can I use inheritance in this way, given that I created the InitCar class only to inherit it and am not going to use objects of this class explicitly.
Before refactoring. People and License are not my own classes, I cannot change them.
class Car
{
public:
void Move();
void SpeedUp();
void SpeedDw();
//More other
private:
int speed = 0;
std::string name;
int id = 0;
People owner; // not my own class
License license; // not my own class
void InitCarFromConfig()
{
//Here I read the data from the file
}
void InitOwner()
{
//Here I init the People owner
}
void InitInspection()3
{
//Here I init the License license
}
};
After refactoring
class InitCar
{
protected:
std::string name;
int id = 0;
People owner; // not my own class
License license; // not my own class
void InitCarFromConfig()
{
//Here I read the data from the file
}
void InitOwner()
{
//Here I init the People owner
}
void InitInspection()
{
//Here I init the License license
}
};
class Car : InitCar
{
public:
void Move()
{
InitOwner();
}
void SpeedUp();
void SpeedDw();
//More other
private:
int speed = 0;
};
Is this use of inheritance acceptable and are performance issues possible?
Although it is true that you can use inheritance to reduce the size of you classes and reduce code duplication for other classes (which can also inherit InitCar for similar base functionality), it is actually not a good idea.
Functionality-wise, it does work, it does reduce code duplication and class sizes. However, it is a bad design, because it uses inheritance wrong, and breaks concepts of "clean code".
When you create a class, you create an entity which represents something. Inheritance create relations between those entities. Saying that Car inherits InitCar is saying that Car is a sort of InitCar, which logically makes no sense, because InitCar is just a helper class.
You can solve this if the base type was an actual entity, like Vehicle, and you had multiple vehicles. However, your InitClass is specifically intended to split you code, so it doesn't actually make a Vehicle, renaming it won't fix the design.
Composition over inheritance
A well known concept in "clean code", saying that it is better to hold functionality helping classes as variables in the class, rather then inherit from a base class. It is both more flexible for switching implementations, and does not abuse the purpose of inheritance:
class Car {
public:
void Move();
void SpeedUp();
void SpeedDw();
//More other
private:
int speed = 0;
std::string name;
int id = 0;
People owner;
License license;
HelperClass helper; // new class for initing..
void InitCarFromConfig()
{
//data = helper.InitCarFromConfig();
}
void InitOwner()
{
//owner = helper.InitOwnerForCar(param);
}
void InitInspection()
{
//data = helper.InitInspection(param);
}
};
Now we simply delegate our calls to the helper class (whose name is just a stub, you should have a name matching what it does, or maybe several classes). So we do save some space, we don't abuse inheritance and typing, and we now actually have flexibility in implementation, since now we can replace the instance of helper and get a new logic.
How do we init helper? Usually receiving via the constructor is the best idea. But you can create inside the class if you really want to.
Best design for your case
But is it the best design here?! No actually. Because the real problem in the class is the existence of the Init_ methods within the class.
When creating a class, it is important that when the constructor finishes running, the class is completely initialized. When it is not, we create several problems:
Risk a chance that the class is used, and some properties/methods are not complete for use, causing errors
Complexity of the class is increased, making maintenance harder (which is what you pointed as the issue for you).
Limits the users of the class from flexibility in its creation, thus limiting the design options for using the class. Creating tests for example, will be a nightmare.
Very risk for multithreading use, and harder to handle
Instead than, what we can do is receive all the data we need to operate from the constructor, and simply store it:
public:
Car(std::string name, id, People owner, License license);
Now comes another issue: what if it is difficult to perform initialization. After all you have 3 methods for initializing your class, so could be not easy for users. This is were the Factory design pattern comes in. We will create a class, named CarFactory (or so) and use it to create our classes. Within it, it will have all the logic to init the class data:
class CarFactory {
public:
Car* CreateCar(params_from_user) {
// init data
return new Car(data);
}
};
What did we accomplish with this:
We made Car smaller and less complex
We allowed users more options about how to use Car
We maintained the Init option from earlier, to help create Car
Our code is a lot easier to look at and maintain because it is separated logically, and classes are small
Car is fully initialized after constructor call

c++ Factory. Child constructor not accessible from parent

I'm making a socket factory. I want every external application to use the interface of the Socket class that is the parent of a few classes (ServerSocketTCP, ClientSocketTCP, ServerSocketUDP and so on) because eventually socket will be use to read and write independently of the type, simplifying the use of them. So sockets will be only constructed by a socket static member (The factory). That why children constructors are protected in order to avoid users to create them.
Here is where I got the error:
class A{
protected:
A();
public:
static A* createClass(int _type){
switch(_type){
case 0:
return new B();
case 1:
return new C();
default:
return nullptr;
}
}
}
class B: public A{
protected:
B();
}
class C: public A{
protected:
C();
}
Then the compiler says that the constructors of B and C are not accessible from A. Is there any way to do what I want? I thought that it was possible to access children protected member but now I see that not because the access inheritance...
There are problems with your code. Except for missing ; after the class definition you are also implementing the factory in a wrong way.
In general you have a Producer that produces products. The products all share a base class that normal users should not be able to instantiate (e.g. pure virtual or protected ctor). According to what the client chooses, the Producer creates an instance of the product and delivers it back. So if your product ctors are private you need to declare the producer as a friend in order to be able to access the respective ctors.
Now the producer delivers some pointer to a base product which can be downcasted to the type you need. So an compiling example (picked yours and modified it accordingly) would read like this:
class Producer;
class BaseProduct {
protected:
BaseProduct() {}
};
class Product_B : public BaseProduct {
friend class Producer;
private:
Product_B();
};
class Product_C : public BaseProduct {
friend class Producer;
private:
Product_C();
};
class Producer{
private:
Producer();
public:
static BaseProduct* createProduct_Class(int _type){
switch(_type){
case 0:
return new Product_B;
case 1:
return new Product_C;
default:
return nullptr;
}
}
};
Please be aware that using the factory pattern wrongly can result quickly in anti-patterns.
EDIT: Plus you should not forget to extend your producer class to manage deletion etc. There are many books and websites that handle all kinds of patterns. One good book is "Object-oriented Software Engineering from Bernd Brügge", but of course there are a lot more of them.
In the code you've given, the factory method can't even see the B and C class definitions, so it can't possibly use them, no matter whether a parent can access a child's protected members or not (it can't, as noted by Marco A.).
You need to move the implementation of the factory method to a cpp file where it can see all of the class defintions. Then you'll get errors about the constructors being protected, and you can deal with those appropriately (presumably by making friends).
Yes, th compiler is complaining because B and C constructors and `protected, and no friendship exists. So A cannot call those constructors.
The correct design is to separate the Factory type from the class hierarchy, not to put it in the base class.

Private method in a C++ interface?

Why would I want to define a C++ interface that contains private methods?
Even in the case where the methods in the public scope will technically suppose to act like template methods that use the private methods upon the interface implementation, even so, we're telling the technical specs. right from the interface.
Isn't this a deviation from the original usage of an interface, ie a public contract between the outside and the interior?
You could also define a friend class, which will make use of some private methods from our class, and so force implementation through the interface. This could be an argument.
What other arguments are for defining a private methods within an interface in C++?
The common OO view is that an interface establishes a single contract that defines how objects that conform to that interface are used and how they behave. The NVI idiom or pattern, I never know when one becomes the other, proposes a change in that mentality by dividing the interface into two separate contracts:
how the interface is to be used
what deriving classes must offer
This is in some sense particular to C++ (in fact to any language with multiple inheritance), where the interface can in fact contain code that adapts from the outer interface --how users see me-- and the inner interface --how I am implemented.
This can be useful in different cases, first when the behavior is common but can be parametrized in only specific ways, with a common algorithm skeleton. Then the algorithm can be implemented in the base class and the extension points in derived elements. In languages without multiple inheritance this has to be implemented by splitting into a class that implements the algorithm based in some parameters that comply with a different 'private' interface. I am using here 'private' in the sense that only your class will use that interface.
The second common usage is that by using the NVI idiom, it is simple to instrument the code by only modifying at the base level:
class Base {
public:
void foo() {
foo_impl();
}
private:
virtual void foo_impl() = 0;
};
The extra cost of having to write the dispatcher foo() { foo_impl(); } is rather small and it allows you to later add a locking mechanism if you convert the code into a multithreaded application, add logging to each call, or a timer to verify how much different implementations take in each function... Since the actual method that is implemented in derived classes is private at this level, you are guaranteed that all polymorphic calls can be instrumented at a single point: the base (this does not block extending classes from making foo_impl public thought)
void Base::foo() {
scoped_log log( "calling foo" ); // we can add traces
lock l(mutex); // thread safety
foo_impl();
}
If the virtual methods were public, then you could not intercept all calls to the methods and would have to add that logging and thread safety to all the derived classes that implement the interface.
You can declare a private virtual method whose purpose is to be derivated. Example :
class CharacterDrawer {
public:
virtual ~CharacterDrawer() = 0;
// draws the character after calling getPosition(), getAnimation(), etc.
void draw(GraphicsContext&);
// other methods
void setLightPosition(const Vector&);
enum Animation {
...
};
private:
virtual Vector getPosition() = 0;
virtual Quaternion getRotation() = 0;
virtual Animation getAnimation() = 0;
virtual float getAnimationPercent() = 0;
};
This object can provide drawing utility for a character, but has to be derivated by an object which provides movement, animation handling, etc.
The advantage of doing like this instead of provinding "setPosition", "setAnimation", etc. is that you don't have to "push" the value at each frame, instead you "pull" it.
I think this can be considered as an interface since these methods have nothing to do with actual implementation of all the drawing-related stuff.
Why would I want to define a C++
interface that contains private
methods?
The question is a bit ambiguous/contradictory: if you define (purely) an interface, that means you define the public access of anything that connects to it. In that sense, you do not define an interface that contains private methods.
I think your question comes from confusing an abstract base class with an interface (please correct me if I'm wrong).
An abstract base class can be a partial (or even complete) functionality implementation, that has at least an abstract member. In this case, it makes as much sense to have private members as it makes for any other class.
In practice it is rarely needed to have pure virtual base classes with no implementation at all (i.e. base classes that only define a list of pure virtual functions and nothing else). One case where that is required is COM/DCOM/XPCOM programming (and there are others). In most cases though it makes sense to add some private implementation to your abstract base class.
In a template method implementation, it can be used to add a specialization constraint: you can't call the virtual method of the base class from the derived class (otherwise, the method would be declared as protected in the base class):
class Base
{
private:
virtual void V() { /*some logic here, not accessible directly from Derived*/}
};
class Derived: public Base
{
private:
virtual void V()
{
Base::V(); // Not allowed: Base::V is not visible from Derived
}
};

Modeling "optional" inheritance

I'm having trouble deciding on a way to model this type of relationship...
All bosses can do certain things and have certain things (velocities, health, etc.) so these are part of the "main" abstract boss class.
class Boss // An abstract base class
{
//Stuff that all Bosses can do/have and pure virtual functions
};
Now I want to specify a few more pure virtual functions and members for bosses that can shoot. I'm wondering how I should model this? I've considered deriving a ShootingBoss Class from the Boss class, but specific bosses are classes in themselves (with Boss just being an abstract base class that they are derived from.) Thus if ShootingBoss is derived from Boss, and a specific boss derives from ShootingBoss, that boss won't be able to access the protected data in the Boss class.
Boss(ABC) -> ShootingBoss(ABC) -> SomeSpecificBoss(can't access protected data from Boss?)
Basically, I'm wondering what the recommended way to model this is. Any help is appreciated. If more information is needed, I'd be happy to offer.
I think you need to look into Mixin classes.
For example, you could create the following classes:
class Boss {
// Here you will include all (pure virtual) methods which are common
// to all bosses, and all bosses MUST implement.
};
class Shooter {
// This is a mixin class which defines shooting capabilities
// Here you will include all (pure virtual) methods which are common
// to all shooters, and all shooters MUST implement.
};
class ShootingBoss : public Boss, public Shooter
{
// A boss who shoots!
// This is where you implement the correct behaviour.
};
Mixins require multiple inheritance to be used, and there are many pitfalls and complexities to doing so. I suggest you look at answers to questions like this one to ensure that you avoid these pitfalls.
Why not start using interfaces? So, rather than simply uber base class, you spread out your things into capabilities.
struct IBoss : public IObject
{
}
struct ICanShoot : public IObject
{
}
Generally to implement this you derive your interfaces from another interface which allows you to query for an interface.
struct IObject
{
int getId(); // returns a unique ID for this interface.
int addRef();
int release();
bool queryInterface(int id, void** pp);
}
That way, you implement your Boss more easily:
class Boss : public IBoss, public ICanShoot
{
};
It might be overkill for some, but if your class heirachy is all screwed up, this is the best way out of the mess.
Have a look at M$'s IUnknown interface.
There are two different ways of doing this:
1) Mixin classes (already explained)
2) Role playing classes.
Role playing has it's advantages and disadvantages. Roles, that object can play (boss, shooter, whatever) are implemented using containment. They must be derived from the common base interface class, which will have to be downcasted dynamicaly (argh..). Caller will ask object of your class for the role pointer (this is where downcast will come in) and if object can play the role (returned non-NULL pointer) client will call appropriate function of the role.
Main advantage of role playing approach (appart from avoiding multiple inheritance) - it is dynamic. Object can accept new roles at runtime, as opposed to mixin that has to be defined at compile time.
Also it is scalable. In multiple inheritance (mixin) approach if you decide to expand your hierarchy with "Protector" and say that boss can be simple Boss, ShootingBoss, ProtectingBoss, ShootingProtectingBoss, and later expand it ufrther with Сoward (Boss, ShootingBoss, ProtectingBoss, ShootingProtectingBoss, CowardBoss, CowardShootingBoss, CowardProtectingBoss, CowardShootingProtectingBoss) - you see your hierarchy explodes. This is when you need to switch to role playing model, where object will simply have to accept new role Coward. But until you are sure that you need it - stick with mixin classes.
Below is hierarchy sketch for role playing lcases:
class IRole
{
// some very basic common interface here
public:
virtual ~IRole() {}
};
class IBoss : public IRole
{
};
class IShooter : public IRole
{
};
class IProtector : public IRole
{
};
class MultifunctionalPerson
{
public:
bool AcceptRole(IRole* pRole); // pass some concrete role here
IRole* GetRole(int roleID);
};
// your clinet will be using it like that
MultifunctionalPerson& clPerson = ... (coming from somewhere);
// dynamic_cast below may be replaced with static_cast if you are sure
// that role at PROTECTOR_ROLE location is guaranteed to be of IProtector type or NULL
IProtector* pProtector = dynamic_cast<IProtector*>(clPerson.GetRole(PROTECTOR_ROLE));
if( 0 != pProtector )
{
pProtector->DoSomething();
}

When should I use C++ private inheritance?

Unlike protected inheritance, C++ private inheritance found its way into mainstream C++ development. However, I still haven't found a good use for it.
When do you guys use it?
I use it all the time. A few examples off the top of my head:
When I want to expose some but not all of a base class's interface. Public inheritance would be a lie, as Liskov substitutability is broken, whereas composition would mean writing a bunch of forwarding functions.
When I want to derive from a concrete class without a virtual destructor. Public inheritance would invite clients to delete through a pointer-to-base, invoking undefined behaviour.
A typical example is deriving privately from an STL container:
class MyVector : private vector<int>
{
public:
// Using declarations expose the few functions my clients need
// without a load of forwarding functions.
using vector<int>::push_back;
// etc...
};
When implementing the Adapter Pattern, inheriting privately from the Adapted class saves having to forward to an enclosed instance.
To implement a private interface. This comes up often with the Observer Pattern. Typically my Observer class, MyClass say, subscribes itself with some Subject. Then, only MyClass needs to do the MyClass -> Observer conversion. The rest of the system doesn't need to know about it, so private inheritance is indicated.
Note after answer acceptance: This is NOT a complete answer. Read other answers like here (conceptually) and here (both theoretic and practic) if you are interested in the question. This is just a fancy trick that can be achieved with private inheritance. While it is fancy it is not the answer to the question.
Besides the basic usage of just private inheritance shown in the C++ FAQ (linked in other's comments) you can use a combination of private and virtual inheritance to seal a class (in .NET terminology) or to make a class final (in Java terminology). This is not a common use, but anyway I found it interesting:
class ClassSealer {
private:
friend class Sealed;
ClassSealer() {}
};
class Sealed : private virtual ClassSealer
{
// ...
};
class FailsToDerive : public Sealed
{
// Cannot be instantiated
};
Sealed can be instantiated. It derives from ClassSealer and can call the private constructor directly as it is a friend.
FailsToDerive won't compile as it must call the ClassSealer constructor directly (virtual inheritance requirement), but it cannot as it is private in the Sealed class and in this case FailsToDerive is not a friend of ClassSealer.
EDIT
It was mentioned in the comments that this could not be made generic at the time using CRTP. The C++11 standard removes that limitation by providing a different syntax to befriend template arguments:
template <typename T>
class Seal {
friend T; // not: friend class T!!!
Seal() {}
};
class Sealed : private virtual Seal<Sealed> // ...
Of course this is all moot, since C++11 provides a final contextual keyword for exactly this purpose:
class Sealed final // ...
The canonical usage of private inheritance is the "implemented in terms of" relationship (thanks to Scott Meyers' 'Effective C++' for this wording). In other words, the external interface of the inheriting class has no (visible) relationship to the inherited class, but it uses it internally to implement its functionality.
One useful use of private inheritence is when you have a class that implements an interface, that is then registered with some other object. You make that interface private so that the class itself has to register and only the specific object that its registered with can use those functions.
For example:
class FooInterface
{
public:
virtual void DoSomething() = 0;
};
class FooUser
{
public:
bool RegisterFooInterface(FooInterface* aInterface);
};
class FooImplementer : private FooInterface
{
public:
explicit FooImplementer(FooUser& aUser)
{
aUser.RegisterFooInterface(this);
}
private:
virtual void DoSomething() { ... }
};
Therefore the FooUser class can call the private methods of FooImplementer through the FooInterface interface, while other external classes cannot. This is a great pattern for handling specific callbacks that are defined as interfaces.
I think the critical section from the C++ FAQ Lite is:
A legitimate, long-term use for private inheritance is when you want to build a class Fred that uses code in a class Wilma, and the code from class Wilma needs to invoke member functions from your new class, Fred. In this case, Fred calls non-virtuals in Wilma, and Wilma calls (usually pure virtuals) in itself, which are overridden by Fred. This would be much harder to do with composition.
If in doubt, you should prefer composition over private inheritance.
I find it useful for interfaces (viz. abstract classes) that I'm inheriting where I don't want other code to touch the interface (only the inheriting class).
[edited in an example]
Take the example linked to above. Saying that
[...] class Wilma needs to invoke member functions from your new class, Fred.
is to say that Wilma is requiring Fred to be able to invoke certain member functions, or, rather it is saying that Wilma is an interface. Hence, as mentioned in the example
private inheritance isn't evil; it's just more expensive to maintain, since it increases the probability that someone will change something that will break your code.
comments on the desired effect of programmers needing to meet our interface requirements, or breaking the code. And, since fredCallsWilma() is protected only friends and derived classes can touch it i.e. an inherited interface (abstract class) that only the inheriting class can touch (and friends).
[edited in another example]
This page briefly discusses private interfaces (from yet another angle).
Sometimes I find it useful to use private inheritance when I want to expose a smaller interface (e.g. a collection) in the interface of another, where the collection implementation requires access to the state of the exposing class, in a similar manner to inner classes in Java.
class BigClass;
struct SomeCollection
{
iterator begin();
iterator end();
};
class BigClass : private SomeCollection
{
friend struct SomeCollection;
SomeCollection &GetThings() { return *this; }
};
Then if SomeCollection needs to access BigClass, it can static_cast<BigClass *>(this). No need to have an extra data member taking up space.
Private Inheritance to be used when relation is not "is a", But New class can be "implemented in term of existing class" or new class "work like" existing class.
example from "C++ coding standards by Andrei Alexandrescu, Herb Sutter" :-
Consider that two classes Square and Rectangle each have virtual functions for setting their height and width. Then Square cannot correctly inherit from Rectangle, because code that uses a modifiable Rectangle will assume that SetWidth does not change the height (whether Rectangle explicitly documents that contract or not), whereas Square::SetWidth cannot preserve that contract and its own squareness invariant at the same time. But Rectangle cannot correctly inherit from Square either, if clients of Square assume for example that a Square's area is its width squared, or if they rely on some other property that doesn't hold for Rectangles.
A square "is-a" rectangle (mathematically) but a Square is not a Rectangle (behaviorally). Consequently, instead of "is-a," we prefer to say "works-like-a" (or, if you prefer, "usable-as-a") to make the description less prone to misunderstanding.
I found a nice application for private inheritance, although it has a limited usage.
Problem to solve
Suppose you are given the following C API:
#ifdef __cplusplus
extern "C" {
#endif
typedef struct
{
/* raw owning pointer, it's C after all */
char const * name;
/* more variables that need resources
* ...
*/
} Widget;
Widget const * loadWidget();
void freeWidget(Widget const * widget);
#ifdef __cplusplus
} // end of extern "C"
#endif
Now your job is to implement this API using C++.
C-ish approach
Of course we could choose a C-ish implementation style like so:
Widget const * loadWidget()
{
auto result = std::make_unique<Widget>();
result->name = strdup("The Widget name");
// More similar assignments here
return result.release();
}
void freeWidget(Widget const * const widget)
{
free(result->name);
// More similar manual freeing of resources
delete widget;
}
But there are several disadvantages:
Manual resource (e.g. memory) management
It is easy to set up the struct wrong
It is easy to forget freeing the resources when freeing the struct
It is C-ish
C++ Approach
We are allowed to use C++, so why not use its full powers?
Introducing automated resource management
The above problems are basically all tied to the manual resource management. The solution that comes to mind is to inherit from Widget and add a resource managing instance to the derived class WidgetImpl for each variable:
class WidgetImpl : public Widget
{
public:
// Added bonus, Widget's members get default initialized
WidgetImpl()
: Widget()
{}
void setName(std::string newName)
{
m_nameResource = std::move(newName);
name = m_nameResource.c_str();
}
// More similar setters to follow
private:
std::string m_nameResource;
};
This simplifies the implementation to the following:
Widget const * loadWidget()
{
auto result = std::make_unique<WidgetImpl>();
result->setName("The Widget name");
// More similar setters here
return result.release();
}
void freeWidget(Widget const * const widget)
{
// No virtual destructor in the base class, thus static_cast must be used
delete static_cast<WidgetImpl const *>(widget);
}
Like this we remedied all the above problems. But a client can still forget about the setters of WidgetImpl and assign to the Widget members directly.
Private inheritance enters the stage
To encapsulate the Widget members we use private inheritance. Sadly we now need two extra functions to cast between both classes:
class WidgetImpl : private Widget
{
public:
WidgetImpl()
: Widget()
{}
void setName(std::string newName)
{
m_nameResource = std::move(newName);
name = m_nameResource.c_str();
}
// More similar setters to follow
Widget const * toWidget() const
{
return static_cast<Widget const *>(this);
}
static void deleteWidget(Widget const * const widget)
{
delete static_cast<WidgetImpl const *>(widget);
}
private:
std::string m_nameResource;
};
This makes the following adaptions necessary:
Widget const * loadWidget()
{
auto widgetImpl = std::make_unique<WidgetImpl>();
widgetImpl->setName("The Widget name");
// More similar setters here
auto const result = widgetImpl->toWidget();
widgetImpl.release();
return result;
}
void freeWidget(Widget const * const widget)
{
WidgetImpl::deleteWidget(widget);
}
This solution solves all the problems. No manual memory management and Widget is nicely encapsulated so that WidgetImpl does not have any public data members anymore. It makes the implementation easy to use correctly and hard (impossible?) to use wrong.
The code snippets form a compiling example on Coliru.
If you need a std::ostream with some small changes (like in this question) you may need to
Create a class MyStreambuf which derives from std::streambuf and implement changes there
Create a class MyOStream which derives from std::ostream that also initializes and manages an instance of MyStreambuf and passes the pointer to that instance to the constructor of std::ostream
The first idea might be to add the MyStream instance as a data member to the MyOStream class:
class MyOStream : public std::ostream
{
public:
MyOStream()
: std::basic_ostream{ &m_buf }
, m_buf{}
{}
private:
MyStreambuf m_buf;
};
But base classes are constructed before any data members so you are passing a pointer to a not yet constructed std::streambuf instance to std::ostream which is undefined behavior.
The solution is proposed in Ben's answer to the aforementioned question, simply inherit from the stream buffer first, then from the stream and then initialize the stream with this:
class MyOStream : public MyStreamBuf, public std::ostream
{
public:
MyOStream()
: MyStreamBuf{}
, basic_ostream{ this }
{}
};
However the resulting class could also be used as a std::streambuf instance which is usually undesired. Switching to private inheritance solves this problem:
class MyOStream : private MyStreamBuf, public std::ostream
{
public:
MyOStream()
: MyStreamBuf{}
, basic_ostream{ this }
{}
};
If derived class
- needs to reuse code and
- you can't change base class and
- is protecting its methods using base's members under a lock.
then you should use private inheritance, otherwise you have danger of unlocked base methods exported via this derived class.
Sometimes it could be an alternative to aggregation, for example if you want aggregation but with changed behaviour of aggregable entity (overriding the virtual functions).
But you're right, it has not many examples from the real world.
A class holds an invariant. The invariant is established by the constructor. However, in many situations it's useful to have a view of the representation state of the object (which you can transmit over network or save to a file - DTO if you prefer). REST is best done in terms of an AggregateType. This is especially true if you're const correct. Consider:
struct QuadraticEquationState {
const double a;
const double b;
const double c;
// named ctors so aggregate construction is available,
// which is the default usage pattern
// add your favourite ctors - throwing, try, cps
static QuadraticEquationState read(std::istream& is);
static std::optional<QuadraticEquationState> try_read(std::istream& is);
template<typename Then, typename Else>
static std::common_type<
decltype(std::declval<Then>()(std::declval<QuadraticEquationState>()),
decltype(std::declval<Else>()())>::type // this is just then(qes) or els(qes)
if_read(std::istream& is, Then then, Else els);
};
// this works with QuadraticEquation as well by default
std::ostream& operator<<(std::ostream& os, const QuadraticEquationState& qes);
// no operator>> as we're const correct.
// we _might_ (not necessarily want) operator>> for optional<qes>
std::istream& operator>>(std::istream& is, std::optional<QuadraticEquationState>);
struct QuadraticEquationCache {
mutable std::optional<double> determinant_cache;
mutable std::optional<double> x1_cache;
mutable std::optional<double> x2_cache;
mutable std::optional<double> sum_of_x12_cache;
};
class QuadraticEquation : public QuadraticEquationState, // private if base is non-const
private QuadraticEquationCache {
public:
QuadraticEquation(QuadraticEquationState); // in general, might throw
QuadraticEquation(const double a, const double b, const double c);
QuadraticEquation(const std::string& str);
QuadraticEquation(const ExpressionTree& str); // might throw
}
At this point, you might just store collections of cache in containers and look it up on construction. Handy if there's some real processing. Note that cache is part of the QE: operations defined on the QE might mean the cache is partially reusable (e.g., c does not affect the sum); yet, when there's no cache, it's worth to look it up.
Private inheritance can almost always modelled by a member (storing reference to the base if needed). It's just not always worth it to model that way; sometimes inheritance is the most efficient representation.
Just because C++ has a feature, doesn't mean it's useful or that it should be used.
I'd say you shouldn't use it at all.
If you're using it anyway, well, you're basically violating encapsulation, and lowering cohesion. You're putting data in one class, and adding methods that manipulates the data in another one.
Like other C++ features, it can be used to achieve side effects such as sealing a class (as mentioned in dribeas' answer), but this doesn't make it a good feature.