My style of coding includes the following idiom:
class Derived : public Base
{
public :
typedef Base super; // note that it could be hidden in
// protected/private section, instead
// Etc.
} ;
This enables me to use "super" as an alias to Base, for example, in constructors:
Derived(int i, int j)
: super(i), J(j)
{
}
Or even when calling the method from the base class inside its overridden version:
void Derived::foo()
{
super::foo() ;
// ... And then, do something else
}
It can even be chained (I have still to find the use for that, though):
class DerivedDerived : public Derived
{
public :
typedef Derived super; // note that it could be hidden in
// protected/private section, instead
// Etc.
} ;
void DerivedDerived::bar()
{
super::bar() ; // will call Derived::bar
super::super::bar ; // will call Base::bar
// ... And then, do something else
}
Anyway, I find the use of "typedef super" very useful, for example, when Base is either verbose and/or templated.
The fact is that super is implemented in Java, as well as in C# (where it is called "base", unless I'm wrong). But C++ lacks this keyword.
So, my questions:
is this use of typedef super common/rare/never seen in the code you work with?
is this use of typedef super Ok (i.e. do you see strong or not so strong reasons to not use it)?
should "super" be a good thing, should it be somewhat standardized in C++, or is this use through a typedef enough already?
Edit: Roddy mentionned the fact the typedef should be private. This would mean any derived class would not be able to use it without redeclaring it. But I guess it would also prevent the super::super chaining (but who's gonna cry for that?).
Edit 2: Now, some months after massively using "super", I wholeheartedly agree with Roddy's viewpoint: "super" should be private.
Bjarne Stroustrup mentions in Design and Evolution of C++ that super as a keyword was considered by the ISO C++ Standards committee the first time C++ was standardized.
Dag Bruck proposed this extension, calling the base class "inherited." The proposal mentioned the multiple inheritance issue, and would have flagged ambiguous uses. Even Stroustrup was convinced.
After discussion, Dag Bruck (yes, the same person making the proposal) wrote that the proposal was implementable, technically sound, and free of major flaws, and handled multiple inheritance. On the other hand, there wasn't enough bang for the buck, and the committee should handle a thornier problem.
Michael Tiemann arrived late, and then showed that a typedef'ed super would work just fine, using the same technique that was asked about in this post.
So, no, this will probably never get standardized.
If you don't have a copy, Design and Evolution is well worth the cover price. Used copies can be had for about $10.
I've always used "inherited" rather than super. (Probably due to a Delphi background), and I always make it private, to avoid the problem when the 'inherited' is erroneously omitted from a class but a subclass tries to use it.
class MyClass : public MyBase
{
private: // Prevents erroneous use by other classes.
typedef MyBase inherited;
...
My standard 'code template' for creating new classes includes the typedef, so I have little opportunity to accidentally omit it.
I don't think the chained "super::super" suggestion is a good idea- If you're doing that, you're probably tied in very hard to a particular hierarchy, and changing it will likely break stuff badly.
One problem with this is that if you forget to (re-)define super for derived classes, then any call to super::something will compile fine but will probably not call the desired function.
For example:
class Base
{
public: virtual void foo() { ... }
};
class Derived: public Base
{
public:
typedef Base super;
virtual void foo()
{
super::foo(); // call superclass implementation
// do other stuff
...
}
};
class DerivedAgain: public Derived
{
public:
virtual void foo()
{
// Call superclass function
super::foo(); // oops, calls Base::foo() rather than Derived::foo()
...
}
};
(As pointed out by Martin York in the comments to this answer, this problem can be eliminated by making the typedef private rather than public or protected.)
FWIW Microsoft has added an extension for __super in their compiler.
I don't recall seeing this before, but at first glance I like it. As Ferruccio notes, it doesn't work well in the face of MI, but MI is more the exception than the rule and there's nothing that says something needs to be usable everywhere to be useful.
Super (or inherited) is Very Good Thing because if you need to stick another inheritance layer in between Base and Derived, you only have to change two things: 1. the "class Base: foo" and 2. the typedef
If I recall correctly, the C++ Standards committee was considering adding a keyword for this... until Michael Tiemann pointed out that this typedef trick works.
As for multiple inheritance, since it's under programmer control you can do whatever you want: maybe super1 and super2, or whatever.
I just found an alternate workaround. I have a big problem with the typedef approach which bit me today:
The typedef requires an exact copy of the class name. If someone changes the class name but doesn't change the typedef then you will run into problems.
So I came up with a better solution using a very simple template.
template <class C>
struct MakeAlias : C
{
typedef C BaseAlias;
};
So now, instead of
class Derived : public Base
{
private:
typedef Base Super;
};
you have
class Derived : public MakeAlias<Base>
{
// Can refer to Base as BaseAlias here
};
In this case, BaseAlias is not private and I've tried to guard against careless usage by selecting an type name that should alert other developers.
I've seen this idiom employed in many code bases and I'm pretty sure I've even seen it somewhere in Boost's libraries. However, as far as I remember the most common name is base (or Base) instead of super.
This idiom is especially useful if working with class templates. As an example, consider the following class (from a real project):
template <typename TText, typename TSpec>
class Finder<Index<TText, PizzaChili<TSpec>>, MyFinderType>
: public Finder<Index<TText, MyFinderImpl<TSpec>>, Default>
{
using TBase = Finder<Index<TText, MyFinderImpl<TSpec>>, Default>;
// …
}
The inheritance chain uses type arguments to achieve compile-time polymorphism. Unfortunately, the nesting level of these templates gets quite high. Therefore, meaningful abbreviations for the full type names are crucial for readability and maintainability.
I've quite often seen it used, sometimes as super_t, when the base is a complex template type (boost::iterator_adaptor does this, for example)
is this use of typedef super common/rare/never seen in the code you work with?
I have never seen this particular pattern in the C++ code I work with, but that doesn't mean it's not out there.
is this use of typedef super Ok (i.e. do you see strong or not so strong reasons to not use it)?
It doesn't allow for multiple inheritance (cleanly, anyway).
should "super" be a good thing, should it be somewhat standardized in C++, or is this use through a typedef enough already?
For the above cited reason (multiple inheritance), no. The reason why you see "super" in the other languages you listed is that they only support single inheritance, so there is no confusion as to what "super" is referring to. Granted, in those languages it IS useful but it doesn't really have a place in the C++ data model.
Oh, and FYI: C++/CLI supports this concept in the form of the "__super" keyword. Please note, though, that C++/CLI doesn't support multiple inheritance either.
One additional reason to use a typedef for the superclass is when you are using complex templates in the object's inheritance.
For instance:
template <typename T, size_t C, typename U>
class A
{ ... };
template <typename T>
class B : public A<T,99,T>
{ ... };
In class B it would be ideal to have a typedef for A otherwise you would be stuck repeating it everywhere you wanted to reference A's members.
In these cases it can work with multiple inheritance too, but you wouldn't have a typedef named 'super', it would be called 'base_A_t' or something like that.
--jeffk++
After migrating from Turbo Pascal to C++ back in the day, I used to do this in order to have an equivalent for the Turbo Pascal "inherited" keyword, which works the same way. However, after programming in C++ for a few years I stopped doing it. I found I just didn't need it very much.
I was trying to solve this exact same problem; I threw around a few ideas, such as using variadic templates and pack expansion to allow for an arbitrary number of parents, but I realized that would result in an implementation like 'super0' and 'super1'. I trashed it because that would be barely more useful than not having it to begin with.
My Solution involves a helper class PrimaryParent and is implemented as so:
template<typename BaseClass>
class PrimaryParent : virtual public BaseClass
{
protected:
using super = BaseClass;
public:
template<typename ...ArgTypes>
PrimaryParent<BaseClass>(ArgTypes... args) : BaseClass(args...){}
}
Then which ever class you want to use would be declared as such:
class MyObject : public PrimaryParent<SomeBaseClass>
{
public:
MyObject() : PrimaryParent<SomeBaseClass>(SomeParams) {}
}
To avoid the need to use virtual inheritance in PrimaryParenton BaseClass, a constructor taking a variable number of arguments is used to allow construction of BaseClass.
The reason behind the public inheritance of BaseClass into PrimaryParent is to let MyObject have full control over over the inheritance of BaseClass despite having a helper class between them.
This does mean that every class you want to have super must use the PrimaryParent helper class, and each child may only inherit from one class using PrimaryParent (hence the name).
Another restriction for this method, is MyObject can inherit only one class which inherits from PrimaryParent, and that one must be inherited using PrimaryParent. Here is what I mean:
class SomeOtherBase : public PrimaryParent<Ancestor>{}
class MixinClass {}
//Good
class BaseClass : public PrimaryParent<SomeOtherBase>, public MixinClass
{}
//Not Good (now 'super' is ambiguous)
class MyObject : public PrimaryParent<BaseClass>, public SomeOtherBase{}
//Also Not Good ('super' is again ambiguous)
class MyObject : public PrimaryParent<BaseClass>, public PrimaryParent<SomeOtherBase>{}
Before you discard this as an option because of the seeming number of restrictions and the fact there is a middle-man class between every inheritance, these things are not bad.
Multiple inheritance is a strong tool, but in most circumstances, there will be only one primary parent, and if there are other parents, they likely will be Mixin classes, or classes which don't inherit from PrimaryParent anyways. If multiple inheritance is still necessary (though many situations would benefit to use composition to define an object instead of inheritance), than just explicitly define super in that class and don't inherit from PrimaryParent.
The idea of having to define super in every class is not very appealing to me, using PrimaryParent allows for super, clearly an inheritence based alias, to stay in the class definition line instead of the class body where the data should go.
That might just be me though.
Of course every situation is different, but consider these things i have said when deciding which option to use.
I don't know whether it's rare or not, but I've certainly done the same thing.
As has been pointed out, the difficulty with making this part of the language itself is when a class makes use of multiple inheritance.
I use this from time to time. Just when I find myself typing out the base class type a couple of times, I'll replace it with a typedef similar to yours.
I think it can be a good use. As you say, if your base class is a template it can save typing. Also, template classes may take arguments that act as policies for how the template should work. You're free to change the base type without having to fix up all your references to it as long as the interface of the base remains compatible.
I think the use through the typedef is enough already. I can't see how it would be built into the language anyway because multiple inheritence means there can be many base classes, so you can typedef it as you see fit for the class you logically feel is the most important base class.
I use the __super keyword. But it's Microsoft specific:
http://msdn.microsoft.com/en-us/library/94dw1w7x.aspx
I won't say much except present code with comments that demonstrates that super doesn't mean calling base!
super != base.
In short, what is "super" supposed to mean anyway? and then what is "base" supposed to mean?
super means, calling the last implementor of a method (not base method)
base means, choosing which class is default base in multiple inheritance.
This 2 rules apply to in class typedefs.
Consider library implementor and library user, who is super and who is base?
for more info here is working code for copy paste into your IDE:
#include <iostream>
// Library defiens 4 classes in typical library class hierarchy
class Abstract
{
public:
virtual void f() = 0;
};
class LibraryBase1 :
virtual public Abstract
{
public:
void f() override
{
std::cout << "Base1" << std::endl;
}
};
class LibraryBase2 :
virtual public Abstract
{
public:
void f() override
{
std::cout << "Base2" << std::endl;
}
};
class LibraryDerivate :
public LibraryBase1,
public LibraryBase2
{
// base is meaningfull only for this class,
// this class decides who is my base in multiple inheritance
private:
using base = LibraryBase1;
protected:
// this is super! base is not super but base!
using super = LibraryDerivate;
public:
void f() override
{
std::cout << "I'm super not my Base" << std::endl;
std::cout << "Calling my *default* base: " << std::endl;
base::f();
}
};
// Library user
struct UserBase :
public LibraryDerivate
{
protected:
// NOTE: If user overrides f() he must update who is super, in one class before base!
using super = UserBase; // this typedef is needed only so that most derived version
// is called, which calls next super in hierarchy.
// it's not needed here, just saying how to chain "super" calls if needed
// NOTE: User can't call base, base is a concept private to each class, super is not.
private:
using base = LibraryDerivate; // example of typedefing base.
};
struct UserDerived :
public UserBase
{
// NOTE: to typedef who is super here we would need to specify full name
// when calling super method, but in this sample is it's not needed.
// Good super is called, example of good super is last implementor of f()
// example of bad super is calling base (but which base??)
void f() override
{
super::f();
}
};
int main()
{
UserDerived derived;
// derived calls super implementation because that's what
// "super" is supposed to mean! super != base
derived.f();
// Yes it work with polymorphism!
Abstract* pUser = new LibraryDerivate;
pUser->f();
Abstract* pUserBase = new UserBase;
pUserBase->f();
}
Another important point here is this:
polymorphic call: calls downward
super call: calls upwards
inside main() we use polymorphic call downards that super calls upwards, not really useful in real life, but it demonstrates the difference.
The simple answer why c++ doesn't support "super" keyword is.
DDD(Deadly Diamond of Death) problem.
in multiple inheritance. Compiler will confuse which is superclass.
So which superclass is "D"'s superclass?? "Both" cannot be solution because "super" keyword is pointer.
This is a method I use which uses macros instead of a typedef. I know that this is not the C++ way of doing things but it can be convenient when chaining iterators together through inheritance when only the base class furthest down the hierarchy is acting upon an inherited offset.
For example:
// some header.h
#define CLASS some_iterator
#define SUPER_CLASS some_const_iterator
#define SUPER static_cast<SUPER_CLASS&>(*this)
template<typename T>
class CLASS : SUPER_CLASS {
typedef CLASS<T> class_type;
class_type& operator++();
};
template<typename T>
typename CLASS<T>::class_type CLASS<T>::operator++(
int)
{
class_type copy = *this;
// Macro
++SUPER;
// vs
// Typedef
// super::operator++();
return copy;
}
#undef CLASS
#undef SUPER_CLASS
#undef SUPER
The generic setup I use makes it very easy to read and copy/paste between the inheritance tree which have duplicate code but must be overridden because the return type has to match the current class.
One could use a lower-case super to replicate the behavior seen in Java but my coding style is to use all upper-case letters for macros.
Related
This question is the equivalent of Java's How to make Superclass Method returns instance of SubClass
Suppose this class hierarchy:
class A
{
public:
A makeCopyOfObject();
};
class B: public A
{
public:
void doSomethingB();
};
class C: public A
{
public:
void doSomethingC();
};
I'd like to use it this way:
B().makeCopyOfObject().doSomethingB();
C().makeCopyOfObject().doSomethingC();
But of course I can't, because the makeCopyOfObject function returns an instance of A, not an instance of a subclass.
I surely could write two versions of the function in the two subclasses, but the code would be the same, except for the return type, because all fields to be copied and modified are in the base class. So, is there an alternative?
I don't understand what you try to achieve with that and it is probably not an answer (see comments), but what you can do is a template (in detail a Curiously recurring template pattern).
template<typename CRTP>
class A {
public:
CRTP& makeCopyOfObject() {
return static_cast<CRTP&>(*this);
}
};
class B: public A<B> {
public:
void doSomethingB();
};
class C: public A<C> {
public:
void doSomethingC();
};
And use it as you wanted:
b.makeCopyOfObject().doSomethingB();
c.makeCopyOfObject().doSomethingC();
See running example here.
Sidenote:
Because of laziness, even the function is called makeCopyOfObject it does not create a copy, but returns a reference to the object. To do a copy you have to implement copy constructors and return a copy (search for clone pattern).
It's difficult to see any practical use case for this, but it's easy to do with a non-member function template:
template< class Type >
auto copy_of( Type const& o )
-> Type
{ return o; }
Then you can write
copy_of( B() ).doSomething();
to your hearts' content, instead of just writing
B().doSomething();
Enjoy.
For the academic issue of covariant methods, there is a lot to be said. You might check out answers to how to implement a clone method. Essentially, this is not supported by C++ except for type system support for reference or pointer result, so one must do it "manually", and the three common approaches are (1) fully manual implementation in each class, (2) using a macro that expands to necessary code in each class, and (3) a middle-man class that forwards arguments to base class constructors. With C++03 the third way was about the same order of difficulty as leveraging dominance in a virtual inheritance hierarchy, so with C++03 that was also an option to be mentioned. But it's just not in the right ballpark of practicality with C++11 and later, (1), (2) and (3) it is.
First, beware of slicing.
Second, if you want to make a copy of an object, may I suggest
the copy-constructor:
B b1{};
B b2{b1}.doSomethingB();
or even:
B{ B{} }.doSomethingB();
Also, if you want to preserve polymorphic behaviour, always
handle polymorphic classes via smart-pointers or references.
Note that C++ has value-semantics, while Java has reference-semantics, so design-patterns that are good for Java are not necessarily good for C++.
Since once cannot call a overwritten function of a derived class in base class constructor, I would like to emulate this behavior (similar to what C#, Java, ... are doing under the hood).
The most elegant I could come up with (from a signature side of view) is the following:
class Base {
protected:
virtual void init() {
}
template <typename T, typename ...U>
T internal_create(U&& u) {
T instance(std::forward<U>(u)...);
instance.init();
return instance;
}
};
class Derived : public Base {
protected:
Derived() = default;
virtual void init() override {
}
public:
static Derived create() {
return internal_create<Derived>();
}
};
Where create works as a substitute for the constructor (from public point of view) and the only way to instantiate an Object.
Question is whether this could be achieved simpler, since now every derived class has to implement create.
I can't see that your code would compile. And I can't see the point of the virtual init method there, although it does suggest two phase construction. Which is just evil, which you can find out more about by reading Bjarne Stroustrup’s appendix E to “The C++ Programming Language”, especially section E3.5.
The usual methods for doing derived class initialization in a base class constructor are outlined in the FAQ. Since I once convinced Marshall to add that FAQ item, I feel free to also direct you to my own blog.
In the future, remember that it is often a good idea to check out the FAQ first.
Oh, I forgot. The point about the C++ rules for dynamic type during construction, is to provide type safe construction. In Java and C# you can easily introduce a bug where you're accessing some uninitialized members of a derived class, but not in C++.
Two phase construction ditches that type safety, and makes it difficult to write exception safe usage code, in return for the ability to code it up cleanly for an early 1990's compiler (but really, who needs that ability).
The other usual solutions are designed to keep the type safety.
I was wondering if there is a way to declare an object in c++ to prevent it from being subclassed. Is there an equivalent to declaring a final object in Java?
From C++ FAQ, section on inheritance
This is known as making the class
"final" or "a leaf." There are three
ways to do it: an easy technical
approach, an even easier non-technical
approach, and a slightly trickier
technical approach.
The (easy) technical approach is to
make the class's constructors private
and to use the Named Constructor Idiom
to create the objects. No one can
create objects of a derived class
since the base class's constructor
will be inaccessible. The "named
constructors" themselves could return
by pointer if you want your objects
allocated by new or they could return
by value if you want the objects
created on the stack.
The (even easier) non-technical
approach is to put a big fat ugly
comment next to the class definition.
The comment could say, for example, //
We'll fire you if you inherit from
this class or even just /*final*/
class Whatever {...};. Some
programmers balk at this because it is
enforced by people rather than by
technology, but don't knock it on face
value: it is quite effective in
practice.
A slightly trickier technical approach
is to exploit virtual inheritance.
Since the most derived class's ctor
needs to directly call the virtual
base class's ctor, the following
guarantees that no concrete class can
inherit from class Fred:
class Fred;
class FredBase {
private:
friend class Fred;
FredBase() { }
};
class Fred : private virtual FredBase {
public:
...
};
Class Fred can access FredBase's ctor,
since Fred is a friend of FredBase,
but no class derived from Fred can
access FredBase's ctor, and therefore
no one can create a concrete class
derived from Fred.
If you are in extremely
space-constrained environments (such
as an embedded system or a handheld
with limited memory, etc.), you should
be aware that the above technique
might add a word of memory to
sizeof(Fred). That's because most
compilers implement virtual
inheritance by adding a pointer in
objects of the derived class. This is
compiler specific; your mileage may
vary.
No, there isn't really a need to. If your class doesn't have a virtual destructor it isn't safe to derive from it anyway. So don't give it one.
You can use this trick, copied from Stroustrup's FAQ:
class Usable;
class Usable_lock {
friend class Usable;
private:
Usable_lock() {}
Usable_lock(const Usable_lock&) {}
};
class Usable : public virtual Usable_lock {
// ...
public:
Usable();
Usable(char*);
// ...
};
Usable a;
class DD : public Usable { };
DD dd; // error: DD::DD() cannot access
// Usable_lock::Usable_lock(): private member
In C++0x (and as an extension, in MSVC) you can actually make it pretty clean:
template <typename T>
class final
{
private:
friend T; // C++0x, MSVC extension
final() {}
final(const final&) {}
};
class no_derived :
public virtual final<no_derived> // ah, reusable
{};
NO.
The closest you can come is to declare the constructors private, then provide a static factory method.
There is no direct equivalent language construct for this in C++.
The usual idiom to achieve this technically is to declare its constructor(s) private. To instantiate such a class, you need to define a public static factory method then.
As of C++11, you can add the final keyword to your class, eg
class CBase final
{
...
The main reason I can see for wanting to do this (and the reason I came looking for this question) is to mark a class as non subclassable so you can safely use a non-virtual destructor and avoid a vtable altogether.
There is no way really. The best you can do is make all your member functions non-virtual and all your member variables private so there is no advantage to be had from subclassing the class.
This is our ideal inheritance hierarchy:
class Foobar;
class FoobarClient : Foobar;
class FoobarServer : Foobar;
class WindowsFoobar : Foobar;
class UnixFoobar : Foobar;
class WindowsFoobarClient : WindowsFoobar, FoobarClient;
class WindowsFoobarServer : WindowsFoobar, FoobarServer;
class UnixFoobarClient : UnixFoobar, FoobarClient;
class UnixFoobarServer : UnixFoobar, FoobarServer;
This is because the our inheritance hierarchy would try to inherit from Foobar twice, and as such, the compiler would complain of ambiguous references on any members of Foobar.
Allow me to explain why I want such a complex model. This is because we want to have the same variable accessible from WindowsFoobar, UnixFoobar, FoobarClient, and FoobarServer. This wouldn't be a problem, only I'd like to use multiple inheritance with any combination of the above, so that I can use a server/client function on any platform, and also use a platform function on either client or server.
I can't help but feel this is a somewhat common issue with multiple inheritance... Am I approaching this problem from completely the wrong angle?
Update 1:
Also, consider that we could use #ifdef to get around this, however, this will tend to yield very ugly code like such:
CFoobar::CFoobar()
#if SYSAPI_WIN32
: m_someData(1234)
#endif
{
}
... yuck!
Update 2:
For those who want to read more into the background of this issue, I really suggest skimming over the appropriate mailing list thread. Thing start to get interesting around the 3rd post. Also there is a related code commit with which you can see the real life code in question here.
It would work, although you'd get two copies of the base Foobar class. To get a single copy, you'd need to use virtual inheritance. Read on multiple inheritance here.
class Foobar;
class FoobarClient : virtual public Foobar;
class FoobarServer : virtual public Foobar;
class WindowsFoobar : virtual public Foobar;
class UnixFoobar : virtual public Foobar;
However, there are many problems associated with multiple inheritance. If you really want to have the model presented, why not make FoobarClient and FoobarServer take a reference to Foobar at construction time, and then have Foobar& FoobarClient/Server::getFoobar ?
Composition is often a way out of multiple inheritance. Take a example now:
class WindowsFoobarClient : public WindowsFoobar
{
FoobarClient client;
public:
WindowsFoobarClient() : client( this ) {}
FoobarClient& getClient() { return client }
}
However care must be taken in using this in the constructor.
What you are directly after here is virtual inheritance feature of C++. What you are in here for is a maintenance nightmare. This might not be a huge surprise since well-known authors like H. Sutter have been arguing against such use of inheritance for a while already. But this comes from direct experience with code like this. Avoid deep inheritance chains. Be very afraid of the protected keyword - it's use is very limited. This kind of design quickly gets out of hand - tracking down patterns of access to protected variable somewhere up the inheritance chain from lower level classes becomes hard, responsibilities of the code parts become vague, etc., and people who look at your code a year from now will hate you :)
You're in C++, you should get friendly with templates. Using the template-argument-is-a-base-class pattern, you'll not need any multiple inheritance or redundant implementations. It will look like this:
class Foobar {};
template <typename Base> class UnixFoobarAspect : public Base {};
template <typename Base> class WindowsFoobarAspect : public Base {};
template <typename Base> class FoobarClientAspect : public Base {};
template <typename Base> class FoobarServerAspect : public Base {};
typedef UnixFoobarAspect<FoobarClientAspect<Foobar>/*this whitespace not needed in C++0x*/> UnixFoobarClient;
typedef WindowsFoobarAspect<FoobarClientAspect<Foobar> > WindowsFoobarClient;
typedef UnixFoobarAspect<FoobarServerAspect<Foobar> > UnixFoobarServer;
typedef WindowsFoobarAspect<FoobarServerAspect<Foobar> > WindowsFoobarServer;
You might also consider using the curiously recurring template pattern instead of declaring abstract functions to avoid virtual function calls when the base class needs to call a function implemented in one of the specialized variants.
Use virtual inheritance, in the declaration of FoobarClient, FoobarServer, WindowsFoobar and UnixFoobar, put the word virtual before the Foobar base class name.
This will ensure there is always a single instance of Foobar no matter how many times it appears in your base class hierarchy.
Have a look at this search. Diamond inheritance is somewhat of contentuous issue and the proper solution dependes on individual situation.
I would like to comment on the Unix/Windows side of things. Generally one would #ifndef things out that are not appropriate for the particular platform. So you would end up with just Foobar compiled for either Windows or Unix using preprocessor directives, not UnixFoobar and WindowsFoobar. See how far you can get using that paradigm before exploring virtual inheritance.
Try this example of composition and inheritance:
class Client_Base;
class Server_Base;
class Foobar
{
Client_Base * p_client;
Server_Base * p_server;
};
class Windows_Client : public Client_Base;
class Windows_Server : public Server_Base;
class Win32 : Foobar
{
Win32()
{
p_client = new Windows_Client;
p_server = new Windows_Server;
}
};
class Unix_Client : public Client_Base;
class Unix_Server : public Server_Base;
class Unix : Foobar
{
Unix()
{
p_client = new Unix_Client;
p_server = new Unix_Server;
}
};
Many experts have said that issues can be resolved with another level of indirection.
There is nothing "illegal" about having the same base class twice. The final child class will just (literally) have multiple copies of the base class as part of it (including each variable in the base class, etc). It may result in some ambiguous calls to that base classes' functions, though, which you might have to resolve manually. This doesn't sound like what you want.
Consider composition instead of inheritance.
Also, virtual inheritance is a way to fold together the same base class which appears twice. If it really is just about data sharing, though, composition might make more sense.
You can access the variable with the qualified class name, but I forget the exact syntax.
However, this is one of the bad cases of using multiple inheritance that can cause you many difficulties. Chances are that you don't want to have things this way.
It's much more likely you want to have foobar privately inherited, have each subclass own a foobar, have foobar be a pure virtual class, or have the derived class own the things it currently defines or even define foobar on its own.
We have a restriction that a class cannot act as a base-class for more than 7 classes.
Is there a way to enforce the above rule at compile-time?
I am aware of Andrew Koenig's Usable_Lock technique to prevent a class from being inherited but it would fail only when we try to instantiate the class. Can this not be done when deriving itself?
The base-class is allowed to know who are its children. So i guess we can declare a combination of friend
classes and encapsulate them to enforce this rule. Suppose we try something like this
class AA {
friend class BB;
private:
AA() {}
~AA() {}
};
class BB : public AA {
};
class CC : public AA
{};
The derivation of class CC would generate a compiler warning abt inaccessible dtor. We can then flag
such warnings as errors using compiler tweaks (like flag all warnings as errors), but i would not like to rely on such techniques.
Another way, but to me looks rather clumsy is:-
class B;
class InheritanceRule{
class A {
public:
A() {}
~A() {}
};
friend class B;
};
class B {
public:
class C : public InheritanceRule::A
{};
};
class D : public InheritanceRule::A{};
The derivation of class D will be flagged as a compiler error, meaning all the classes to be derived should be derived inside class B. This will allow atleast an inspection of the number of classes derived from class A but would not prevent anyone from adding more.
Anyone here who has a way of doing it ? Better still if the base-class need not know who are its children.
NOTE: The class which acts as a base-class can itself be instantiated (it is not abstract).
Thanks in advance,
EDIT-1: As per Comment from jon.h, a slight modification
// create a template class without a body, so all uses of it fail
template < typename D>
class AllowedInheritance;
class Derived; // forward declaration
// but allow Derived by explicit specialization
template<>
class AllowedInheritance< Derived> {};
template<class T>
class Base : private AllowedInheritance<T> {};
// privately inherit Derived from that explicit specialization
class Derived : public Base<Derived> {};
// Do the same with class Fail Error
// it has no explicit specialization, so it causes a compiler error
class Fail : public Base<Fail> {}; // this is error
int main()
{
Derived d;
return 0;
}
Sorry, I don't know how to enforce any such limit using the compiler.
Personally I wouldn't bother trying to force the rule into the code itself - you are cluttering the code with stuff that has nothing to do with what the code is doing - it's not clean code.
Rather than jumping through hoops, I'd try to get that rule relaxed. Instead it should be a guideline that could be broken if necessary and in agreement with others in the team.
Of course, I lack the knowledge of exactly what you're doing so the rule could be appropriate, but in general it probably isn't.
Any programming "rule" that says you must never do x or you must always do y is almost always wrong! Notice the word "almost" in there.
Sometimes you might need more than 7 derived classes - what do you do then? Jump through more hoops. Also, why 7? Why not 6 or 8? It's just so arbitrary - another sign of a poor rule.
If you must do it, as JP says, static analysis is probably the better way.
I'm tired as crap, can barely keep my eyes open, so there's probably a more elegant way to do this, and I'm certainly not endorsing the bizarre idea that a Base should have at most seven subclasses.
// create a template class without a body, so all uses of it fail
template < typename D, typename B> class AllowedInheritance;
class Base {};
class Derived; // forward declaration
// but allow Derived, Base by explicit specialization
template<> class AllowedInheritance< Derived, Base> {};
// privately inherit Derived from that explicit specialization
class Derived : public Base, private AllowedInheritance<Derived, Base> {};
// Do the same with class Compiler Error
// it has no explicit specialization, so it causes a compiler error
class CompileError: public Base,
private AllowedInheritance<CompileError, Base> { };
//error: invalid use of incomplete type
//‘struct AllowedInheritance<CompileError, Base>’
int main() {
Base b;
Derived d;
return 0;
}
Comment from jon.h:
How does this stop for instance: class Fail : public Base { }; ? \
It doesn't. But then neither did the OP's original example.
To the OP: your revision of my answer is pretty much a straight application of Coplien's "Curiously recurring template pattern"]
I'd considered that as well, but the problem with that there's no inheritance relationship between a derived1 : pubic base<derived1> and a derived2 : pubic base<derived2>, because base<derived1> and base<derived2> are two completely unrelated classes.
If your only concern is inheritance of implementation, this is no problem, but if you want inheritance of interface, your solution breaks that.
I think there is a way to get both inheritance and a cleaner syntax; as I mentioned I was pretty tired when I wrote my solution. If nothing else, by making RealBase a base class of Base in your example is a quick fix.
There are probably a number of ways to clean this up. But I want to emphasize that I agree with markh44: even though my solution is cleaner, we're still cluttering the code in support of a rule that makes little sense. Just because this can be done, doesn't mean it should be.
If the base class in question is ten years old and too fragile to be inherited from, the real answer is to fix it.
Lots of the various static code analysis tools provide information about inheritance hierarchy. Rather than try and handle it in your code, I would look into a tool that could set up some rules for inheritance hierarchy and fail the build if those rules are not followed. Might cost a little $ and you might have to write a custom rule (I've seen inheritance depth, but not inheritance "breadth" like you want). But, in the long run, I think that's your best bet.
Per comment: I've used Coverity with some success. Bit spendy. There are several good SO threads that may have better options.
Rather than cluttering the code with assertions, you might be able to use something like GCC-XML, which parses C++ source using the g++ compiler frontend and generates XML output. I expect that it would be reasonably straightforward to develop a tool that parses this output and checks for violations of the rule; this could then be integrated with source code check-in.
BTW, having base classes know about their descendants violates the Open-Closed Principle, meaning that it actually undercuts the usefulness of OO programming in general. The main reason for separating code into base classes and subclasses is so that the base class does not have to know about its subclasses -- this makes possible things like plugin packages delivered after installation.