What I've seen and been taught about encapsulation is that we can have data members as private and member functions are public.
But C++ Primer defines encapsulation as:
Separation of implementation from interface; encapsulation hides
the implementation details of a type. In C++, encapsulation is enforced by putting the implementation in the private part of a class.
The last line is the confusing part: putting the implementation in the private part of a class. By implementation, he means the function definitions, right? I mean, I've never seen a function declared public (as prototype) and implemented in private.
I'm really confused. Please explain what he's trying to say with a simple example.
The concept being explained is more abstract than you're thinking about it. The "interface" is "what callers expect the object to do". And the implementation is technically how the class actually carries out those operations.
So for example, take a List class. Code that uses a List should only care about its interface: things like addObject(), clear(), getSize(), sort().
But the implementation of List -- which callers should not care about -- may vary drastically on how to accomplish this. For example the data could be stored as a linked list. Or maybe as a dynamic array. This is "private" implementation details that only the List class needs to care about. There will indeed probably be a private: method called reallocate() or so. Callers should never use this; it's an implementation detail -- not part of the public interface. Callers should not care how the List allocates its storage.
Similarly, a sort() method implies it will sort objects in the list. That's the interface. But the implementation may use any number of algorithms to perform the sort. The implementation is a private detail - and may be done in private methods. In any case it's hidden from callers.
template<typename T>
class List
{
public:
// public members are part of the interface: the externally-visible behavior "contract" your object guarantees.
void addObject(const T& obj)
{
// call private methods to help carry out implementation.
ensureCapacity(this->sizeAllocated + 1);
this->sizeAdvertized += 1;
// ... and copy the object into the right position in this->data...
}
size_t getSize() const
{
return this->sizeAdvertized;
}
// ... other members like clear(), sort()...
private:
T* data;
size_t sizeAllocated;
size_t sizeAdvertized;
// this needs to be private because it's not part of the interface. Callers
// should never need to call this.
void ensureCapacity(size_t requestedCapacity)
{
if(sizeAllocated >= requestedCapacity)
return;// already have enough storage available.
// ... reallocate this->data, copy existing items to the new array...
this->sizeAllocated = requestedCapacity;
}
};
And finally to address what you said:
I mean, I've never seen a function declared public (as prototype) and implemented in private.
"Private" again is more abstract than you're thinking. The implementation of a class is basically always "private" in that it's hidden from callers. It doesn't necessarily mean the private: access specifier. It just means that it's not exposed to callers. Implementation of public methods fits this description.
You can indeed have private functions (methods) in a class. Consider:
class X
{
public:
// public interface - this never changes and you provide documentation for it
void do_something();
private:
// this private interface is likely to change. consumers of this class
// are prevented from calling these methods unless they are friends
void first_private_thing();
void second_private_thing();
};
// definition
void X::do_something()
{
// private implementation in public method
first_private_thing();
second_private_thing();
}
there are further extensions on this theme, for example:
class Base
{
public:
// public non-virtual interface
void do_something();
private:
// calls private virtual implementation
virtual void do_something_impl() = 0;
};
// definition:
void Base::do_something()
{
do_something_impl();
}
Related
I am studying this code:
#include <iostream>
class A
{
public:
A() {};
void fox(A& otherA) { otherA.hello(); }
protected:
void hello() {std::cout << "hello" << std::endl;}
};
A a1,a2;
int main(void)
{
a1.fox(a2);
a1.hello();
}
and am a bit confused as to how saying a1.fox(a2) will compile while saying a1.hello() will not. I would have assumed it would break because while I can call protected and private functions from within a class...allowing me to do that on the otherA object means I would have to be aware that I am calling it from within a member of it's own class. Why/how does this work?
Protected is not instance-by-instance access control, it's a class-by-class access control.
main() (which is not in any class) cannot call private or protected methods of any class at all; hence it fails to call a1.hello().
The implementation of A::fox(A&), on the other hand, is inside the class A, so it can call its private and protected methods, both on itself and on other instances of the class.
Because A is making the call to otherA.hello();. You cannot call into it private or protected code directly, but descendants of A, including A itself, can call into A (descendants cannot access A's private data/methods, but A can access A's private data/methods). Relatedly, A can also access the private data/methods of other instances of A (this is generally how copy constructors and assignment operators work).
In fact, it's the ability to use protected code within the class that enables the creation of some very powerful OO concepts. With that said, I see it as an abuse to call an inner-object's private or protected methods even when possible, but using them directly against yourself is hopefully by design rather than convenience.
In C++, you can provide abstract implementations of classes (or structs for that matter) by marking items as virtual and not providing an implementation.
class A
{
public:
void set_value(const std::string &value)
{
if (is_valid(value))
{
this->value = value;
}
}
const std::string &get_value() const
{
return value;
}
protected:
virtual boolean is_valid(const std::string &value) const = 0;
private:
std::string value;
}
Then
class B : public A
{
protected:
virtual boolean is_valid(const std::string &value) const
{
return value != "abc";
}
}
Notice that A is setup to inherit functionality, and it is built to anticipate it being supplied (granted the example above doesn't really provide a lot of utility, but it does show what I mean).
The access control in C++ is at class level. Not instance level.
Compiler can't possibly know if otherA is actually the same instance or not. You need runtime support to actually determine the identity of the instance to provide such access control.
Apart from the performance problem that this presents, the objective of C++ is to catch errors at compile time, not execution time. As stroustrup says, data-encapsulation and type-safety features can't prevent someone from doing fraud (when the program has unmediated access to all allocated memory).
Now, why is it ok to settle for a solution without runtime check. An anology could help - because as an implementor of a class, you won't rob your own house.
I have a question about declaration of class.
I read the following lines in a paper: A C++ class declaration combines the external interface of an object with the implementation of that interface.
So, what is a external interface in C++? are there concept of interface in C++? how to understand this: A C++ class declaration combines the external interface of an object with the implementation of that interface. ?
I think it's referring to the API — i.e. the signatures of the public functions — as contrasted to the implementation — i.e. private functions and data members.
class T
{
// Here are some private things.
// You might say that these are part of
// the class's implementation.
int x;
int y;
void foo();
void bar();
public:
// And here are some public things, that
// constitute the class's API or "interface",
// which is the mechanism by which you may
// interact with objects of this type.
void baz();
void boz();
};
Notice how they are all present, right there, in the single class definition, and they must be. "Combined".
Ultimately, though, you'd have to ask the author of the paper as the terminology level used is up to them. Conceivably they could be talking about inheritance heirarchies and abstract base classes... though I can't find a way to rationalise the assertion that C++ class definitions "combine" those in any real sense.
I think the definition by the paper is a bit inaccurate. The terms declaration, implementation, definition, and interface should be used with some rigor. I will try to explain a little bit.
First of all, a class declaration does not specify any interface: it simply states that the class exists. For instance, these are some declarations:
class my_class;
struct my_structure;
template<typename T> class X;
A class definition on the other hand declares which are the members of a class (functions and data). Without entering too much into details, the term external interface in the sense used by the paper you quote roughly means "a specification of what can be done with objects of that class by code which belongs to functions that are not members of that class".
Here is an example of a class definition:
class my_class
{
public:
void foo();
int bar(int x) const;
private:
void do_something();
int data;
};
The term external interface used in the paper you mention almost certainly refers to the public interface, which is the list of all members of the class which have public visibility. All member variables and functions of a class can have one of three levels of visibility: public, protected, or private. I am not delving into details here, but it should be enough to say that public members (data or functions) are those members that can be accessed from functions which are not themselves members of the class, while private members can only be accessed from functions which are members of the class. The protected qualifier is related with inheritance and I don't think that needs to be covered to answer your question.
Now the public interface of class my_class above declares functions foo() and bar(), but does not yet specify their implementation or, in more formal terms, their definition. In general, member functions are not necessarily defined in a class definition (you can't tell what foo() does just by looking at the definition of my_class, can you?). Thus, unless you write the body of a member function directly after its declaration, a separate member function definition is necessary to specify the implementation of that function:
void my_class::foo()
{
std::cout << "hello, i'm foo" << std::endl;
}
int my_class::bar(int x)
{
do_something();
x * 2 + 1;
}
void my_class::do_something()
{
std::cout << "doing something..." << std::endl;
}
Due to the different visibility levels of these functions, a client code from a function external to class my_class can call functions foo() and bar(), because they belong to the public interface, but not function do_something(), which is declared as private. For instance:
int main()
{
my_class c;
c.foo(); // OK!
c.do_something(); // ERROR!
}
The rationale behind the fact that some functions can be made accessible from the outside of a class and other cannot is to be found in a good design principle that goes under the name of "information hiding". By exposing to your clients only a set of services and hiding the way those services are actually implemented (e.g. function bar() invokes the private function do_something()), you create a layer of abstraction that protects client code from possible internal changes in the implementation of those services.
So finally, I believe that what the writer of the sentence "A C++ class declaration combines the external interface of an object with the implementation of that interface" actually wants to say is that from the definition of a class you can get a hint on what are the services that class exposes to its clients ("external interface", i.e. public functions) and what are the functions and variables that are used internally to realize those services ("implementation", i.e. private functions and member variables).
I apologize if it took a bit long to finally give you the interpretation of that sentence, but I felt like some clarification was in order. Anyway, this was necessarily just a short summary of this articulated topic: I am sure you can find better sources if you google all these terms or if you buy a good book on C++.
P.S.: Also please keep in mind, that formally the term (and keyword!) interface means something very specific in C++, which requires introducing the notion of pure virtual function. I thought it was not the case of explaining that, as it was likely unrelated with the intended meaning of the word "interface" in the sentence you quoted.
You could view the public members of a class as an external interface.
There is no interface in C++ as you have it in Java, for example. You can only define a base class and define some virtual member functions, which must be implemented by derived classes.
A class declaration includes public, protected and/or private members. The protected and private members could be seen as "implementation" details, but not necessarily as implementation of that public interface.
The interface contains declaration of the method, and this is found in header files. This header files is correlated with some source files where appear the code for this methods. fr example, you can see how can be add a class in Eclipse CDT.
So, I am willing to structure my project like that:
ClassA.cpp:
class ClassA {
public:
static ClassA* create() {
return new ClassA();
}
void methodA() {
// stuff here
}
void methodB() {
// more stuff here
}
private:
ClassA() {
}
void privateMethodOne() {
//yadda yadda
}
int attributeA;
char attributeB;
};
ClassA.hpp:
class ClassA {
public:
ClassA* create();
void methodA();
void methodB();
private:
ClassA();
};
I am going to work only with pointers, I wonder if this approach would generate an error in a future. I wonder if there is a pitfall here. Suppose that the .hpp is automatically generated so it would have exactly the same members, except the private ones.
This approach is not valid. C++ has the one definition rule. See C++03 section 3.2 for full details, but here is Wikipedia's summary (highlighting is mine):
In short the ODR states that:
In any translation unit, a template, type, function, or object can have no more than one definition. Some of these can have any number of declarations. A definition provides an instance.
In the entire program, an object or non-inline function cannot have more than one definition; if an object or function is used, it must have exactly one definition. You can declare an object or function that is never used, in which case you don't have to provide a definition. In no event can there be more than one definition.
Some things, like types, templates, and extern inline functions, can be defined in more than one translation unit. For a given entity, each definition must be the same. Non-extern objects and functions in different translation units are different entities, even if their names and types are the same.
You may be looking for the PIMPL idiom, which is a way to "hide" private members from the public interface (i.e. the public header file).
As the OP expressed a wish to:
"...hide the private attributes so you dont have to deploy new headers if the amount of attributes changes"
then I would solve this by seperating interface from implementation. You expose the interface and hide the implementation.
What you could expose to those needing to use the class is a thin interface instead of a class declaration. A thin interface in C++ is best described with pure virtual functions. You would also expose a function which returns the object that implements this interface.
Firstly the header file which exposes your API. This is all the users of the service will see:
struct Interface1 {
virtual ~Interface1() {}
virtual void methodA()=0;
};
Interface1* createInstanceOfInterface1();
Then in files that the user of your service does not see we have the implementation:
class Interface1Impl : public Interface1 {
private:
int nTopSecretMemberVar;
public:
virtual void methodA() {
//implement it
}
};
Interface1* createInstanceOfInterface1() {
return new Interface1Impl();
}
And the usage of your API by the peoplse using the service who are not exposed to the details of the implementation, as follows:
void test() {
Interface1* p = createInstanceOfInterface1();
p->methodA();
}
This becomes a particularly valuable practice when it makes sense to place the implementation of such services in DLLs or shared libraries that can be plugged and played at run time. It yields many benefits.
This is actually double definition of class A
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
}
};
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.