Re: Initialising private base members in copy constructor
On Aug 6, 8:18 pm, "Fraser Ross" <a...@b.com> wrote:
template<typename T,
typename CounterPolicy = SimpleReferenceCount,
typename ObjectPolicy = StandardObjectPolicy>
class CountingPtr : private CounterPolicy, private ObjectPolicy {
private:
// shortcuts:
typedef CounterPolicy CP;
typedef ObjectPolicy OP;
T* object_pointed_to;
public:
// copy constructor:
CountingPtr (CountingPtr<T,CP,OP> const& cp)
: CP((CP const&)cp), // copy policies
OP((OP const&)cp) {
this->attach(cp); // copy pointer and increment counter
}
I'm not sure why the casts work. Why wasn't static_cast used
instead?
Because static_cast doesn't ignore the private. This is the one
thing that you can only do with a C style cast. Except that
here...
Since the inheritances are private I'm surprised that casts can be done.
Some compilers don't appear to even require a cast at all.
At this point, you're in the context of CountingPtr, so you have
access to the private bases. No cast is required, and IMHO,
it's very bad policy to use one. (If you have to, of course,
static_cast is to be preferred, but in general, the conversion
to base is one of the foundations of OO programming, to the
point of being an exception to the rule that implicit
conversions should be avoided.)
Outside of CountingPtr, of course, static_cast won't work, but a
C style cast will. (I don't know why the standard says this.
Some historical reason, probably.) In general, however, private
inheritance is (or should be) an implementation detail; outside
of the class, you should code as if it wasn't there.
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34