Is it possible to create a class that derives from two or more CWindowImpl-derived classes? Maybe with virtual inheritance? I was trying to do something like this, in order to take advantage of CHAIN_MSG_MAP:
class CClassOne : public virtual CWindowImpl<CClassOne>
{
public:
BEGIN_MSG_MAP(CClassOne)
// ...
END_MSG_MAP()
}
class CClassTwo : public virtual CWindowImpl<CClassTwo>
{
public:
BEGIN_MSG_MAP(CClassTwo)
// ...
END_MSG_MAP()
}
class CClassThree : public CClassOne, public CClassTwo
{
public:
BEGIN_MSG_MAP(CClassThree)
CHAIN_MSG_MAP(CClassOne)
CHAIN_MSG_MAP(CClassTwo)
END_MSG_MAP()
}
But when I instantiate CClassThree and try to call SubclassWindow, I get an ambiguous-access compilation error. So does anybody know how to do this?
You don't need to inherit from 2+ CWindowImpl bases (and it does not make much sense overall too). Instead, as you have more choices for your message map in Message Map Macros (ATL), you would prefer to have separate classes with message map referencing them via CHAIN_MSG_MAP_MEMBER or have a composite control with chaining to multiple members, for example (depending on relation between your windows, whether they are peers or parent/child ones).
Related
This is an unexpected issue I've run into. I'm writing a GUI application, and I use two classes from the GUI library: a Model class and a View class. The Model contents are rendered by the View class to the screen. At some point I decided to derive the Model class because I needed extended functionality. The library's classes are meant to be derived and I found many examples. It was easy and workd perfectly.
Now there's a problem: the Model class offers methods for direct editing of the model data. I don't want these methods to be public because I wrote wrappers, and these wrappers have to be the only way to edit. I do need the inheritance because my derived MyModel overrides many virtual methods of the Model class. So I was thinking what to do. Here's a summary with all details:
There's a BasicModel class which offers methods for iteration through the model data
There's a Model class, which inherits BasicModel, and extends it by also offering methods for editing the data (I think BaseModel is abstract and has no data, and Model defines internal data structures and implements the iteration interface offered by BasicModel)
There's a MyModel class which inherits Model. It overrides many virtual methods, has extended editing mechanism and wants to hide the lower-level editing methods offered by Model
There's a View class which stores a pointer to a BasicModel object. Thus the View uses only the iteration interface, and doesn't even know about any editing interfaces.
So I want to keep MyModel's iteration interface public, so that I can pass it to my View object, but hide the editing interface offered by Model.
Solutions I thought of:
Solution 1: Inheritance can't be avoided because I have to iverride virtual methods, but the solution itself doesn't have to use inheritance: I can write a wrapper to the MyModel class, which offers access to a const reference to the encapsulated MyModel object and offers wrappers to MyModel's editing mechanism. It may be ugly because of all the wrappers, but it avoids messing with multiple inheritance and access specifiers.
Solution 2: Have MyModel inherit Model. No multiple inheritance. Now go to MyModel's class definition in MyModel.hpp and write method declarations of all Model's editing methods, under protected ir private, so that they're hidden. This works very well, but there's one little problem with maintenance: If in future versions of the library, the Model interface changes, e.g. a new editing method is added, we'll have to add it manually to the MyModel class as a private/protected method. Of course I can track the library's changes, or at least go to its online API reference and have a glance at the Model class reference page, just to make sure nothing's changes, or update my code if necessary, before a production/stable version of my application is released.
Solution 3: Use multiple inheritance, and then I have no idea what's supposed to happen. Is it safe or not. Is the behavior compiler dependent or not. This is the idea: MyModel inherits from Model and from basicModel: public inheritance from BasicModel (for the iteration interface) and protected/private inheritance from Model (in order to hide Model's editing interface).
Notes:
Note 1: My high-level editing mechanism uses Model's lower-level editing methods.
Note 2: The virtual methods MyModel overrides, some of them are defined by BasicModel (thus inherited by Model too) and some don't exist in BasicModel and are defined by Model (e.g. methods related to drag-n-drop).
Note 3: The GUI library I use is gtkmm, the C++ binding of GTK+, and the classes I'm talking about are Gtk::TreeModel, Gtk::TreeStore, Gtk::TreeView and my own MyModel class, which derives from Gtk::TreeStore. I ignored these names because the question is a general OO planning question, but I'm mentioning the real classes here so that people who are familiar them will understand the problem much more easily.
I'm not sure what would be the best design here. Definitely solution 3 is the one with the lowest maintenance cost. It's actually zero, because the inheritance access specifiers just do all the work automatically. The question is, does solution 3 always work as expected, e.g. for an iteration method, will compilers make it public (because of public inheritance from BasicModel) or private (because of private inheritance from Model, which is derived from BasicModel). I never used multiple inheritance like this...
Pseudo-Code
This is more or less how the library works:
namespace GUI
{
class BasicModel
{
public:
/* iteration interface for observing the model */
iterator get_iter();
// but no data here, it's just an interface which calls protected virtual methods
// which are implemented by deriving classes, e.g. Model
protected:
virtual iterator get_iter_vfunc() = 0;
virtual void handle_signal();
};
class Model : public BasicModel
{
/* inherits public iteration interface*/
/* implements observation virtual methods from BasicModel*/
virtual iterator get_iter_vfunc() { /*...*/ }
/* has private data structures for the model data */
std::vector<Row> data;
/* has public editing interface, e.g. insert_row(), erase(), append()
/* has protected drag-n-drop related virtual methods*/
virtual void handle_drop();
};
}
My code:
class MyModel : public GUI::Model
{
/* implements virtual methods from BasicModel, e.g. default signal handlers*/
virtual void handle_signal() { /*...*/ }
/* implements drag-n-drop virtual methods from Model*/
virtual void handle_drop() { *...* }
/* inherits public iteration interface*/
/* inherits public editing interface (***which I want to hide***)
/* implements its own editing mechanism*/
void high_level_edit (int param);
};
Experiment with GCC
I tried the following code, compiled with warnings off (otherwise GCC complains):
#include <iostream>
class Base
{
public:
void func ()
{
std::cout << "Base::func() called" << std::endl;
func_vfunc ();
}
protected:
virtual void func_vfunc ()
{
std::cout << "Base::func_vfunc() called" << std::endl;
}
};
class Derived : public Base
{
protected:
virtual void func_vfunc ()
{
std::cout << "Derived::func_vfunc() called" << std::endl;
}
};
class MyClass : public Base, private Derived
{
};
int main (int argc, char* argv[])
{
Base base;
Derived derived;
MyClass myclass;
base.func ();
derived.func ();
myclass.func ();
return 0;
}
For some reason GCC insists the call myclass.func() is ambigous, but one of the func()s us supposed to be private because of the private inheritance, so I don't understand why it cannot compile. Bottom line, assuming it's not a bug but just me not understanding how things work - the suggested solution of multiple inheritance is impossible. The only way to fix this problem, if I'm not mistaken, is virtual inheritance, but I can't use it because the classes I use are library classes and they don't use virtual inheritance. And even then, since I use private and public inheritance together, it may not solve the problem and still be an ambigous call.
EDIT: I tried making Derived and MyClass derive virtually from Base, and it fully solves the problem. But in my case, I can't change library classes, so it's not an option.
If I understand your problem correctly, you should probably use a mix of inheritance (MyModel derives from BaseModel) and composition (MyModel contains a private instance of Model).
Then in MyModel use your own implementation of the base virtual methods, and for the ones you don't want to reimplement just make them a proxy to the corresponding Model methods.
Anyway, IMHO you should avoid multiple inheritance if you can. It can get pretty hairy over time otherwise.
EDIT: Now that I can see the code, I'll give it another shot.
What you need to do is reimplement whatever you need in a class MyModelImpl (derives from Model) which will be hidden inside a proxy class MyModel (derives from BaseModel). My first idea was very similar except I didn't understood that you needed to reimplement some parts of Model.
Something along the lines of:
class MyModel : public BaseModel {
public:
void high_level_edit(int param) { m_impl.high_level_edit(param); }
protected:
virtual iterator get_iter_vfunc() { return m_impl.get_iter_vfunc(); }
virtual void handle_signal() { m_impl.handle_signal(); }
private:
class MyModelImpl : public Model {
public:
void high_level_edit(int param);
// reimplement whatever you need (methods present in BaseModel,
// you need to call them from MyModel proxies)
virtual iterator get_iter_vfunc() { /*...*/ }
protected:
// reimplement whatever you need (methods present only in Model,
// you don't need to call them from MyModel proxies)
virtual void handle_drop();
};
MyModelImpl m_impl;
};
I believe that should work correctly since there is no actual state (data) in BaseModel, unless there is something I misunderstood again...
You can do something like
class MyModel : protected Model
{
public:
using Model::iterator;
//it will make iterator public in MyModel
}
if I understand the case correctly, and provided Model doesn't inherit privately from iterable class, which must be the case here, I guess. Pardon me if I said something stupid. I'm not a very experienced coder.
It's a bit hard to explain in words, so I'll give an example:
(The following code might have incorrect syntax but it suffices to give an idea)
class A
{
public:
static void Update(UINT someValue);
};
class B : public A
{
public:
static void Update(UINT someValue);
};
class C : public A
{
public:
static void Update(UINT someValue);
};
I know static members function do not override each other,
but let's suppose they do.
What I want to achieve, is when A::Update(someValue); is called,
It should implicitly call B::Update(someValue), and also C::Update(someValue), as well as call every static void Update(UINT someValue) method of other classes derived from A
Is this possible in one way or another?
And if it is, how would you do it?
I think you should be using composite pattern instead. You can read about it at http://en.wikipedia.org/wiki/Composite_pattern and http://www.javacamp.org/designPattern/composite.html
That info below my comment is not enough to have a clear idea about your code but I was thinking if it is possible to do something similar to what C# does with events, where you can register events and the class that triggers then (your base class in that case) can implement a list of function pointers (pointing to the derived methods, which in that case you have to have instances of the derived classes) and call all of then iterating this list. Just an idea, don't know if this is what you need.
There's no way to do it automatically. A simple way to get the effect is for each derived class to call the function of its base class:
class A
{
public:
static void Update(UINT someValue) {
std::cout << "A\n";
}
};
class B : public A
{
public:
static void Update(UINT someValue) {
A::Update(someValue);
std::cout << "B\n";
}
};
If you prefer to work from bottom to top, you could have each class do its work before calling the derived class. Of course there's nothing to stop a derived class from implementing Update and not calling its base class. It is however fine for a class to not implement Update at all -- it doesn't care about updates, but its base class's function can still be called. So it's not a huge burden on implementers, they just have to follow the rule that if they implement the function, they have to call the base.
Another way might be for the base class to keep a list of "listeners" who are interested in updates, and to call them in turn whenever an update occurs. Each derived class can then register a suitable listener.
It might be difficult to make code like this exception-safe, though, if each level makes changes but one or more levels may throw.
Suppose I have following inheritance tree:
SDLBullet inherits from Bullet inherits from Entity
EnemyBullet inherits form Bullet inherits from Entity
Now I need a new class, SDLEnemyBullet, which needs the draw as implemented in SDLBullet, and the collision as implemented in EnemyBullet. How would I do this? Is this to be solved using multiple inheritance? If not, feel free to edit my question and title. If so, how would I implement such thing?
Some code examples below:
class Entity {
bool collision(Entity) = 0;
void draw() = 0;
}
class Bullet : Entity {
bool collision(Entity) {/*some implementation*/};
void draw() {/*draw me*/};
}
class SDLBullet : Bullet {
void draw() {/*draw me using SDL*/};
}
class EnemyBullet : Bullet {
bool collision(Entity) {/*if Entity is a fellow enemy, don't collide*/};
}
class SDLEnemyBullet : ????? {
/*I need SDLBullet::draw() here*/
/*I need EnemyBullet::collision(Entity) here*/
/*I certainly do not want EnemyBullet::draw nor SDLBullet::collision here*/
}
Any help is much appreciated!
(BTW: This is a school project, and an inheritance tree like this was suggested to us. No one is stopping us from doing it different and better. Thats why I asked the question.)
The textbook solution involves multiple and virtual inheritance.
class SDLBullet : public virtual Bullet {
void draw() {/*draw me using SDL*/};
};
class EnemyBullet : public virtual Bullet {
bool collision(Entity) {/*if Entity is a fellow enemy, don't collide*/};
};
class SDLEnemyBullet : public SDLBullet, public EnemyBullet {
// just one Bullet subobject here
};
Normally, collision stuff is done using multiple dispatch, or in C++, who hasn't this feature, using the visitor pattern.
BUT
why don't you have a hierarchy like this instead ?
class Entity;
class Bullet : public Entity
{
public:
virtual draw();
}
class FriendlyBullet : public Bullet
{
public:
bool collide(EnnemyBullet*);
bool collide(FriendlyBullet*);
}
class EnnemyBullet : public Bullet
{
public:
bool collide(EnnemyBullet*);
bool collide(FriendlyBullet*);
}
This would work too, and wouldn't require multidispatch or multiple inheritance
You need to specify a comma separated list of the super classes:
class SDLEnemyBullet : public SDLBullet, public EnemyBullet {
/*I need SDLBullet::draw() here*/
/*I need EnemyBullet::collision(Entity) here*/
/*I certainly do not want EnemyBullet::draw nor SDLBullet::collision here*/
}
It looks like you're making a game (engine). To avoid the need for complex inheritance structures like this favor composition over inheritance for entities i.e. Have an entity object that contains separate 'component' objects for rendering etc. That way you can mix and match the components however you like without having an explosion of classes with all the different combinations of super classes.
Here's a good article on the subject: http://cowboyprogramming.com/2007/01/05/evolve-your-heirachy/
Prefer composition over inheritance
You don't need inheritance to combine stuff that's not related like that. Make up basic objects (entities?) for game logic, physics, sound, input, graphics (which may use inheritance) and combine those a GameObject which just has an array of said objects.
Some nifty cross-linking is useful since they will all share a Frame or Transform, but that can be done during creation by iterating over all other objects and using dynamic_cast... (it's useful if you do not need to depend on initialization order).
But there's really no need to build this with inheritance. It doesn't fit your usecase properly. (Although virtual inheritance is useful, it's not a good thing to use inheritance to force different things to become the same, i.e. making everything be a something, instead of being made up of different parts (render, damage, sound, etc...).
Read this and this for more info, or just click the title to google for it. :)
I'm developing a GUI library with a friend and we faced the problem of how to determine whether a certain element should be clickable or not (Or movable, or etc.).
We decided to just check if a function exists for a specific object, all gui elements are stored in a vector with pointers to the base class.
So for example if I have
class Base {};
class Derived : public Base
{
void example() {}
}
vector<Base*> objects;
How would I check if a member of objects has a function named example.
If this isn't possible than what would be a different way to implement optional behaviour like clicking and alike.
You could just have a virtual IsClickable() method in your base class:
class Widget {
public:
virtual bool IsClickable(void) { return false; }
};
class ClickableWidget : public Widget
{
public:
virtual bool IsClickable(void) { return true; }
}
class SometimesClickableWidget : public Widget
{
public:
virtual bool IsClickable(void);
// More complex logic punted to .cc file.
}
vector<Base*> objects;
This way, objects default to not being clickable. A clickable object either overrides IsClickable() or subclasses ClickableWidget instead of Widget. No fancy metaprogramming needed.
EDIT: To determine if something is clickable:
if(object->IsClickable()) {
// Hey, it's clickable!
}
The best way to do this is to use mixin multiple inheritance, a.k.a. interfaces.
class HasExample // note no superclass here!
{
virtual void example() = 0;
};
class Derived : public Base, public HasExample
{
void example()
{
printf("example!\n");
}
}
vector<Base*> objects;
objects.push_back(new Derived());
Base* p = objects[0];
HasExample* he = dynamic_cast<HasExample*>(p);
if (he)
he->example();
dynamic_class<>() does a test at runtime whether a given object implements HasExample, and returns either a HasExample* or NULL. However, if you find yourself using HasExample* it's usually a sign you need to rethink your design.
Beware! When using multiple inheritance like this, then (HasExample*)ptr != ptr. Casting a pointer to one of its parents might cause the value of the pointer to change. This is perfectly normal, and inside the method this will be what you expect, but it can cause problems if you're not aware of it.
Edit: Added example of dynamic_cast<>(), because the syntax is weird.
If you're willing to use RTTI . . .
Instead of checking class names, you should create Clickable, Movable, etc classes. Then you can use a dynamic_cast to see if the various elements implement the interface that you are interested in.
IBM has a brief example program illustrating dynamic_cast here.
I would create an interface, make the method(s) part of the interface, and then implement that Interface on any class that should have the functionality.
That would make the most sense when trying to determine if an Object implements some set of functionality (rather than checking for the method name):
class IMoveable
{
public:
virtual ~IMoveable() {}
virtual void Move() = 0;
};
class Base {};
class Derived : public Base, public IMoveable
{
public:
virtual void Move()
{
// Implementation
}
}
Now you're no longer checking for method names, but casting to the IMoveable type and calling Move().
I'm not sure it is easy or good to do this by reflection. I think a better way would be to have an interface (somethign like GUIElement) that has a isClickable function. Make your elements implement the interface, and then the ones that are clickable will return true in their implementation of the function. All others will of course return false. When you want to know if something's clickable, just call it's isClickable function. This way you can at runtime change elements from being clickable to non-clickable - if that makes sense in your context.
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();
}