c++ Inheritance and shared pointers - c++

Here is the situation. Let's say we have a virtual base class (e.g. ShapeJuggler) which contains a method that takes a shared pointer to a virtual base class object (e.g. Shape) as argument. Let's jump into the following pseudo-code to understand:
class Shape {
}
class ShapeJuggler {
virtual void juggle(shared_ptr<Shape>) = 0;
}
// Now deriving a class from it
class Square : public Shape {
}
class SquareJuggler : public ShapeJuggler {
public:
void juggle(shared_ptr<Shape>) {
// Want to do something specific with a 'Square'
// Or transform the 'shared_ptr<Shape>' into a 'shared_ptr<Square>'
}
}
// Calling the juggle method
void main(void) {
shared_ptr<Square> square_ptr = (shared_ptr<Square>) new Square();
SquareJuggler squareJuggler;
squareJuggler.juggle(square_ptr); // how to access 'Square'-specific members?
}
make_shared or dynamic/static_cast don't seem to do the job.
Is it at all possible? Any ideas, suggestions?
Thanks

This is where std::dynamic_pointer_cast (or one of its friends) comes into play.
It's just like dynamic_cast, but for std::shared_ptrs.
In your case (assuming the Shape class is polymorphic so dynamic_cast works):
void juggle(shared_ptr<Shape> shape) {
auto const sq = std::dynamic_pointer_cast<Square>(shape);
assert(sq);
sq->squareSpecificStuff();
}

This is the multiple dispatch problem. Their are many solution to this problem, the cleanest might be using the visitor pattern, but if you just have one function that need multiple dispatch you could avoid using a visitor:
class SquareJuggler;
class TriangleJuggler;
//.... others concrete jugglers.
class Shape {
//The default behaviour for any juggler and any shape
virtual void juggle_by(Juggler& t) {
//default code for any shape an juggle
}
// list each juggler for which you may
// implement a specific behavior
virtual void juggle_by(SquareJuggler& t) {
//provides default behavior in case you will not
// create a specific behavior for a specific shape.
//for example, just call the unspecific juggler:
this->Shape::juggle_by(static_cast<Juggler&>(t));
}
virtual void juggle_by(TriangleJuggler& t) {
//provides default behavior in case you will not
//create a specific behavior for a specific shape.
//for example, just call the unspecific juggler:
this->Shape::juggle_by(static_cast<Juggler&>(t));
}
//...
};
// Now deriving a class from it
class Square : public Shape {
void juggle_by(SquareJuggler& s) override{
//code specific to SquareJuggler and Shape
}
};
class Triangle : public Shape {
void juggle_by(TriangleJuggler& t) override{
//code specific to TriangleJuggler and Shape
}
};
class ShapeJuggler {
virtual void juggle(shared_ptr<Shape> s) {
//by default (if default has sense):
s->juggle_by(*this);
}
};
class SquareJuggler: public ShapeJuggler {
public:
void juggle(shared_ptr<Shape> s) override {
s->juggle_by(*this);
}
};
class TriangleJuggler: public ShapeJuggler {
public:
void juggle(shared_ptr<Shape> s) override {
s->juggle_by(*this);
}
};
// Calling the juggle method
void main(void) {
shared_ptr<Square> square_ptr = (shared_ptr<Square>) new Square();
SquareJuggler squareJuggler;
squareJuggler.juggle(square_ptr);
//This last call, will perform two virtual calls:
// 1. SquareJuggler::juggle(shared_ptr<Shape);
// 2. Square::juggle_by(SquareJuggler&);
}
You could also defines your XXXJuggler as final, which will enable some devirtualization optimization.

Related

C++ visitor pattern multiple components

I got an object tree. In the object tree I store SceneNodes. A SceneNode is usually the base class for other classes.
I want to implement different behavior for the objects that represent the SceneNodes.
The correct Pattern for this problem should be the visitor pattern. I want to iterate over the SceneNodes and want to call different functions based on the objects stored behind the SceneNodes.
But I not only want to allow one object in the object tree to be one component of the visitor pattern but to share functionality.
For example: I have a BaseObject. I can update this BaseObject (e.g. to a new position) and I can draw a BaseObject (OpenGL stuff).
But I also have a Camera object. The camera object can be updated but not drawn.
Here is the implementation of the Visitor Stuff:
class Visitor
{
public:
virtual void VisitUpdate(ComponentUpdate* element) = 0;
virtual void VisitDraw(ComponentDraw* element) = 0;
virtual void VisitOverlay(ComponentOverlay* element) = 0;
};
Visitor Component:
class Component
{
public:
virtual ~Component() { }
virtual void accept(Visitor* visitor) = 0;
};
Concrete Component:
class ComponentUpdate : public Component
{
public:
void accept(Visitor* visitor) override {
visitor->VisitUpdate(this);
}
virtual void update() = 0;
};
class ComponentDraw : public Component
{
public:
void accept(Visitor* visitor) override {
visitor->VisitDraw(this);
}
virtual void draw() = 0;
};
And finally a concrete visitor:
class SceneNodeVisitor : public Visitor
{
void VisitUpdate(ComponentUpdate* element) override {
element->update();
}
void VisitDraw(ComponentDraw* element) override {
element->draw();
}
};
Now I'd like to do something like this:
class Camera : public ComponentUpdate
{
void update() override { std::cout << "Camnera update" << std::endl; }
};
class ObjectBase : public ComponentDraw, public ComponentUpdate
{
void update() override { std::cout << "ObjectBase update" << std::endl; }
void draw() override { std::cout << "ObjectBase draw" << std::endl; }
};
Ok, so far so good. The problem I have now is that the compiler says "base class is ambiguous". I think this is not correct because ObjectBase is ambiguous because it has two different accept() functions, am I right?
Is there a way to use the visitor pattern so that I can freely anoint the classes with the functionality I need for them?
Here the main function:
int main() {
ObjectBase ob;
Camera cam;
SceneNodeVisitor visitor;
std::vector<Component*> components;
components.push_back(new Camera);
components.push_back(new ObjectBase);
components[0]->accept(&visitor);
components[1]->accept(&visitor);
}
Strange is that I can create the ObjectBase on the stack. I only get the error if I try to create the object on the heap (via new).
Pastebin is down at the moment, I can give you this example code as soon as it's up again.
Okay, I'm not entirely sure, but I think you should separate out some of the concepts you're doing.
As soon as you inherit from two classes that both inherit from the same base class, you need to start looking at virtual inheritance. That might solve your problem. But the path from ObjectBase to Component is either through ComponentDraw or ComponentUpdate. In effect, you probably have two copies of Component because you're not using virtual inheritance.
I would strongly consider using the concept of interfaces. While C++ technically doesn't have them, you can make them, anyway.
And look at virtual inheritance.

How to refer to instances of a class universally without type codes?

I was making a text based RPG in which I have an abstract Item class. From this Item class, I have the classes Weapon, Potion, Key, and Armor. The main character class, Protagonist uses these items and has a function doItemEffect(Item*). How do I implement doItemEffect(Item*) in a way that I refer to all items in universally? To better phrase my problem, if I wasn't clear, here is an example that uses a quite ugly solution.
class Protagonist
{
public:
void doItemEffect(Item* it)
{
switch(it->getType()) //<-- The type is an enum class
{
case ItemType::WEAPON:
attackOpponent(it.getAttackPower()); //If it is a weapon it would have this function
break;
case ItemType::POTION:
heal(it.getHealPower()); //If it is a weapon it would have this function
break;
case ItemType::KEY:
//..Code..
break;
case ItemType::ARMOR:
//More Code...
break;
}
};
And an example of two of the classes Potion and Weapon (The type of the class is a private variable stored in Item with a mutator method setType()):
class Potion : public Item
{
int healPower;
public:
Potion(std::string name, std::string description) : Item(name, description)
{
setType(ItemType::POTION);
}
//Code
};
Weapon:
class Weapon : public Item
{
int attackPower;
public:
Weapon(std::string name, std::string description) : Item(name, description)
{
setType(ItemType::WEAPON);
}
//Code
};
As you can see, this code relies on an class code and a switch in the Protagonist class. Because of this, this doesn't seem very object oriented or polymorphic. Thus, is there a way I could get what subclass a type of Item is, without having to use class codes? Or is there any other solution? The other problem with this snippet above is also that whenever I refer to an item outside of its class, I have to use the same switch statement for each type of item.
Create a virtual function use() in your Item class. Override this function from your derived classes to trigger the various actions (attack, heal, etc.), so that all your subclassed items have an abstract interface to use/apply them.
You can either use RTTI (e.g. dynamic_cast<>()) as an alternative to a dedicated type field:
class Protagonist
{
public:
void doItemEffect(Item* it)
{
Potion *potion = dynamic_cast<Potion *>(item);
Weapon *weapon = dynamic_cast<Weapon *>(item);
if (potion != nullptr) {
heal(potion->getHealPower());
}
else if (weapon != nullptr) {
attackOpponent(weapon->getAttackPower());
}
or use polymorphism by adding a virtual effect() class member function in the abstract Item class:
class Item {
// ...
public:
virtual void effect(Protagonist *) = 0;
// ...
};
and overriding it in the derived classes:
class Potion : public Item
{
// ...
public:
void effect(Protagonist *) override;
};
which has the drawback that your Potion class needs to know that it can be used by a Protagonist. To remedy this, double dispatch is often used. The problem being that C++ does not support double dispatch as a language feature. It can be simulated using the visitor pattern as such:
class Weapon;
class Potion;
class DispatchReceiver {
public:
virtual void effect(Weapon *) = 0;
virtual void effect(Potion *) = 0;
};
class Item {
// ...
public:
virtual void effect(DispatchReceiver *) = 0;
// ...
};
class Potion : public Item {
// ...
virtual void effect(DispatchReceiver *dr) override
{
dr->effect(this);
}
// ...
};
class Weapon : public Item {
// ...
public:
virtual void effect(DispatchReceiver *dr) override
{
dr->effect(this);
}
// ...
};
class Protagonist : public DispatchReceiver {
// ...
public:
void effect(Weapon *weapon) override
{
attackOpponent(weapon->getAttackPower());
}
void effect(Potion *potion) override
{
heal(potion->getHealPower());
}
void doItemEffect(Item* it)
{
it->effect(this);
}
};
Have a list of item types
template<class...Types>
struct type_list_t{};
using Items=type_list_t<Potion, Weapon, etc>;
this replaces your enum. You can write get index of type, and get type from (compile time) index. You can even write what I call a magic switch, mapping runtime (bounded) index to a compile time type via continuation passing style.
Next add a visit method to Item. It takes a index into the type list and then static casts this to the type of the child, then invokes a passed-in callback with the result of the cast.
Write function overloads that look like this:
void use_item( Protagonist*, Potion* );
void use_item( Protagonist*, Weapon* );
Then dispatch to it using visit in Protagonist.
Now you can simplify this by using a pre written variant.
template<class Base, class...Ts>
struct poly_variant:boost::variant<Ts...>{
using boost::variant<Ts...>::variant;
Base& base();
Base const& base() const;
};
now you can visit in Protagonist. A variant of this can be used if you want to make the storage be a pointer (or a smart pointer).
Write base() via apply visitor.

Whether using dynamic cast for providing input for derived class virtual function is recommended?

I read some of the answers in What is the proper use case for dynamic_cast.
The line which best matched my situation here is
#include<iostream>
class Shape
{
public:
virtual void draw()=0;
virtual ~Shape(){};
};
class Rectangle : public Shape
{
public:
int length;
int breath;
void draw()
{
std::cout<<"RECTANGE"<<std::endl;
}
};
class Circle : public Shape
{
public:
int diameter;
void draw()
{
std::cout<<"CIRCLE"<<std::endl;
}
};
/*Abstract Factory*/
Shape* getShapeObj(int type)
{
switch(type)
{
case 1:
return new Rectangle;
case 2:
return new Circle;
/* many types will be added here in future. */
}
return NULL;
};
void drawShapes(Shape *p_shape[],int len)
{
for(int i=0;i<len;i++)
p_shape[i]->draw();
}
int main()
{
Shape *l_shape[2];
l_shape[0]=getShapeObj(1);
l_shape[1]=getShapeObj(2);
Rectangle *l_rec=dynamic_cast<Rectangle*>(l_shape[0]);
if(l_rec)
{
l_rec->length=10;
l_rec->breath=20;
}
Circle *l_circle=dynamic_cast<Circle*>(l_shape[1]);
if(l_circle)
l_circle->diameter=25;
drawShapes(l_shape,2);
}
Essentially, virtual functions only work in some cases, not all of them.
My problem is to pass the input for the virtual function and inputs will vary from type to type. Whether using dynamic cast is recommended here?
The solution is perfect forwarding of function parameters, introduced in c++11.
template<typename ...CtorArgs>
Shape* getShapeObj(int type, CtorArgs&& ctor_args...)
{
switch(type)
{
case 1:
return new Rectangle(std::forward<CtorArgs>(ctor_args)...);
// many types will be added here in future.
}
return NULL;
}
Obviously making the function a template, defeats the purpose of hiding the hierarchy (as well as forcing rather strict requirements on the number of parameters to the constructors). But if the base contains a map of functions that do the construction, which each derived class updates with a pointer to function that constructs it, you can still have information hiding.
I have recently written an answer about storing type erased function pointers in a map, with some static type checking forwarded to run time.
In this particular case, looks like your main function is taking too much responsibility. What if you have Circle, Hexagon, MyFancyFigure types? All of them should be initialized in main in different branches?
It would be much better to move that "initialization" logic to a separate virtual function init in your classes (or even to the constructor). The code would look like this:
class Shape
{
public:
virtual void draw()=0;
virtual void init()=0;
virtual ~Shape(){};
};
class Rectangle : public Shape
{
public:
int length;
int breath;
void draw()
{
//Draw Rectangle
}
void init()
{
length = 10;
breath = 20;
}
};
int main()
{
Shape *l_shape=getShapeObj(1);
// Calls different code of "init" method depending on the actual object type
l_shape->init();
l_shape->draw();
delete l_shape;
}
Also, please note that this initialization logic may be place in some other place, like constructor of the class or the factory method. But main is definitely the wrong place.

Parent class referencing child variable

I have several similar classes inheriting from the same Base-Class/Interface (Base class 1), and they share a couple similar functions, but then also have their own distinct functions. They all also have their own member variables of different classes, and each of those inherits from the same Base-Class/Interface (Base class 2). Is it possible to define a variable in Base class 1, of type Base class 2, then in the actual implementation of classes using Base class 1, have the variable of type Base class 2 be its proper type. Kinda hard to explain, so simplified example below.
//Base-Class 1
class Shape
{
public Shape() {}
ShapeExtra m_var;
//The common functions
public GetVar(){ return m_var; }
}
class Circle : Shape
{
public Circle() { m_var = new CircleExtra(); }
public void CircleFunc()
{
m_var.CircleExtraFunc();
}
}
class Triangle : Shape
{
public Triangle() { m_var = new TriangleExtra(); }
public void TriangleFunc()
{
m_var.TriangleExtraFunc();
}
}
.
.
.
//Base_Class 2
class ShapeExtra
{
public ShapeExtra() {}
}
class CircleExtra : ExtraClass
{
public CircleExtra() {}
void CircleExtraFunc() {//Do stuff}
}
class TriangleExtra : ExtraClass
{
public TriangleExtra() {}
void TriangleExtra() {//Do stuff}
}
.
.
.
So, I need the m_var in the child classes to be kept it as its own unique version. Because right now (w/o the extra CircleExtra m_var;), the GetVar() works, but in CircleFunc, m_var is still type of ShapeExtra, and thus doesn't know that CircleExtraFunc exists. I could cast m_var each time I wanted to do that, but that is repetitive and not worth it in my real-world case. Is there a way to utilize the functions in unique classes based off of ShapeExtra, while keeping the GetVar() function in Shape?
Please ask questions if there is anything I left out.
Simply with inheritance and without using pointers it is not possible, as C++ is a statically-and-strictly-typed language.
You can inherit both the variable and the function, but you'll need to cast function return value.
You can also override the function to make it return the concrete type, but then you have to cast the variable inside the function.
You can also declare the same var with the concrete class in subclasses, but then you just hide the variable in the superclass and inherit nothing.
I'd rather go for a solution using templates. Make the type of the variable a template type and extend the template using a concrete type in subclasses. It'll work perfectly.
It's been a long time since I last programmed in C++ and I beg your pardon if there are errors in the following example. I'm sure you can easily make it work.
template <class S>
class Shape {
S m_var;
//......
public:
S var () {
return m_var;
}
//.......
}
class Circle: Shape <CircleExtra> {
// var method returns CircleExtra
//......
}
Edit:
Regarding some comment, to allow virtual invocation of the method, it is possible to use correlated return types. Something like the following example.
class Shape {
public:
virtual ShapeExtra *var () = 0;
}
template <typename SE>
class ConcreteShape: Shape {
public:
virtual SE *var() {
return &m_var;
}
// Constructor, etc.
private:
SE m_var;
}
Or some variation. Now concrete shapes can benefit from extending the template, as long as SE * is correlated with ShapeExtra * (the type parameter extends ShapeExtra). And you can vall the method transparently through Shape interface.
Using pointers, this is totally possible.
Using your example, you could do something like this:
#include <iostream>
#include <memory>
using namespace std;
//Extras
class ShapeExtra
{
public:
ShapeExtra() {}
void ShapeFunc() { std::cout << "Shape"; }
virtual ~ShapeExtra() = default; //Important!
};
class Shape
{
public:
std::unique_ptr<ShapeExtra> m_var;
//require a pointer on construction
//make sure to document, that Shape class takes ownership and handles deletion
Shape(ShapeExtra* p):m_var(p){}
//The common functions
ShapeExtra& GetVar(){ return *m_var; }
void ShapeFunc() {m_var->ShapeFunc();}
};
class CircleExtra : public ShapeExtra
{
public:
void CircleExtraFunc() {std::cout << "Circle";}
};
class Circle : public Shape
{
CircleExtra* m_var;
public:
Circle() : Shape(new CircleExtra()) {
m_var = static_cast<CircleExtra*>(Shape::m_var.get());
}
void CircleFunc()
{
m_var->CircleExtraFunc();
}
};
int main() {
Circle c;
//use the ShapeExtra Object
c.GetVar().ShapeFunc();
//call via forwarded function
c.ShapeFunc();
//call the circleExtra Function
c.CircleFunc();
return 0;
}
Test it on ideone
Note the use of pointers and a virtual destructor:
By using a virtual destructor in the ShapeExtra base class, you make it possible to destruct an object of any derived class, using a ShapeExtra*. This is important, because
by using a std::unique_ptr<ShapeExtra> instead of a plain C-pointer, we make sure that the object is properly deleted on destruction of Shape.
It is probably a good idea to document this behaviour, i.e. that Shape takes the ownership of the ShapeExtra*. Which especially means, that we do not delete CirleExtra* in the Circle destructor
I decided here to require the ShapeExtra* on construction, but its also possible to just use std::unique_ptr::reset() later and check for nullptr on dereferencing Shape::m_var
Construction order is this: On calling the constructor of Circle, we first create a new CircleExtra which we pass to Shape before finally the constructor of Circle is executed.
Destruction order is Circle first (was created last), then Shape which also destructs the ShapeExtra for us, including (via virtual function) the CircleExtra
I would recommend the following approach:
class ShapeExtra
{
public:
virtual ~ShapeExtra() { }
virtual void SomeCommonShapeFunc() { std::cout << "Shape"; }
};
class Shape
{
public:
virtual ShapeExtra &GetVar() = 0; // Accessor function.
};
Note that the class Shape does not have any data members at all. After that for each derived class you need:
class CircleExtra : public ShapeExtra
{
public:
void SomeCommonShapeFunc() { std::cout << "Circle"; }
};
class Circle : public Shape
{
CircleExtra m_var; // Data member with circle specific class.
public:
virtual ShapeExtra &GetVar() { return m_var; }
};
Implementation of virtual method in Circle will return reference to the base class ShapeExtra. This will allow using this extra in the base class.
Note that pointers and templates are not used at all. This simplifies the overall design.

C++ Overload an overrided method

Is it possible in C++ to overload in the child classes an overrided method?
I'm asking this because I have many child classes that although they are the same (in my case game objects) they interact in different ways with each others.
So, I need to create a function like void processCollision(GameObject obj) in the superclass.
But that could be overloaded in the child classes depending on the class of the GameObject (if it's a building, a car ...).
I'm just trying to run from the alternative which is using upcasting and RTTI.
What you're trying to implement is normally called "multiple dispatch" and unfortunately C++ doesn't support it directly (because in C++ view methods are bounded with classes and there are no multimethods).
Any C++ solution will require some coding for the implementation.
One simple symmetric way to implement it is to create a map for the supported cases:
typedef void (*Handler)(Obj *a, Obj *b);
typedef std::map<std::pair<OType, OType>, Handler> HandlerMap;
HandlerMap collision_handlers;
then the collision handling is:
HandlerMap::iterator i =
collision_handlers.find(std::make_pair(a->type, b->type));
if (i != collision_handlers.end()) i->second(a, b);
and the code goes in a free function.
If speed is a key factor and the object type can be coded in a small integer (e.g. 0...255) the dispatch could become for example:
collision_handlers[(a->type<<8)+b->type](a, b);
where collision handler is just an array of function pointers, and the speed should be equivalent to a single virtual dispatch.
The wikipedia link at the start of the answer lists another more sophisticated option for C++ (the visitor pattern).
"I'm just trying to run from the alternative which is using upcasting and RTTI."
Virtual polymorphism doesn't need upcasting or RTTI. Usually that's what virtual member functions are for:
class GameObject {
public:
virtual void processCollision(GameObject& obj);
};
class SomeGameObject1 : public GameObject {
public:
// SomeGameObject1's version of processCollision()
virtual void processCollision(GameObject& obj) {
// e.g here we also call the base class implementation
GameObject::processCollision();
// ... and add some additional operations
}
};
class SomeGameObject2 : public GameObject {
public:
// SomeGameObject2's version of processCollision()
virtual void processCollision(GameObject& obj) {
// Here we leave the base class implementation aside and do something
// completely different ...
}
};
MORE ADDITIONS AND THOUGHTS
As you're mentioning upcasting I'd suspect you want to handle collisions differently, depending on the actual GameObject type passed. This indeed would require upcasting (and thus RTTI) like follows
class Building : public GameObject {
public:
virtual void processCollision(GameObject& obj) {
Car* car = dynamic_cast<Car*>(&obj);
Airplane* airplane = dynamic_cast<Airplane*>(&obj);
if(car) {
car->crash();
}
else if(airplane) {
airplane->crash();
collapse();
}
void collapse();
};
Based on the above, that makes me contemplative about some design/architectural principles:
May be it's not the best idea to place the processCollision() implementation strategy to the GameObject classes themselves. These shouldn't know about each other (otherwise it will be tedious to introduce new GameObject types to the model)
You should introduce a kind of GameManager class that keeps track of moving/colliding GameObject instances, and chooses a GameObjectCollisionStrategy class implementing void processCollision(GameObject& a,GameObject& b); based on the actual types of a and b.
For choosing the strategy, and resolve the final GameObject implementations and corresponding strategies, you should concentrate all of that business knowdlege to a CollisionStrategyFactory, and delegate to this.
The latter would look something like this
class GameObjectCollisionStrategy {
public:
virtual processCollision(GameObject& a,GameObject& b) const = 0;
};
class CollideBuildingWithAirplane : public GameObjectCollisionStrategy {
public:
virtual void processCollision(GameObject& a,GameObject& b) const {
Building* building = dynamic_cast<Building*>(a);
Airplane* airplane = dynamic_cast<Airplane*>(b);
if(building && airplane) {
airplane->crash();
building->collapse();
}
}
};
class CollideBuildingWithCar : public GameObjectCollisionStrategy {
public:
virtual void processCollision(GameObject& a,GameObject& b) const {
Building* building = dynamic_cast<Building*>(a);
Car* car = dynamic_cast<Car*>(b);
if(building && car) {
car->crash();
}
}
};
class CollisionStrategyFactory {
public:
static const GameObjectCollisionStrategy& chooseStrategy
(GameObject* a, GameObject* b) {
if(dynamic_cast<Building*>(a)) {
if(dynamic_cast<Airplane*>(b)) {
return buildingAirplaneCollision;
}
else if(dynamic_cast<Car*>(b)) {
return buildingCarCollision;
}
}
return defaultCollisionStrategy;
}
private:
class DefaultCollisionStrategy : public GameObjectCollisionStrategy {
public:
virtual void processCollision(GameObject& a,GameObject& b) const {
// Do nothing.
}
};
// Known strategies
static CollideBuildingWithAirplane buildingAirplaneCollision;
static CollideBuildingWithCar buildingCarCollision;
static DefaultCollisionStrategy defaultCollisionStrategy;
};
class GameManager {
public:
void processFrame(std::vector<GameObject*> gameObjects) {
for(std::vector<GameObject*>::iterator it1 = gameObjects.begin();
it1 != gameObjects.end();
++it1) {
for(std::vector<GameObject*>::iterator it2 = gameObjects.begin();
it2 != gameObjects.end();
++it2) {
if(*it1 == *it2) continue;
if(*it1->collides(*it2)) {
const GameObjectCollisionStrategy& strategy =
CollisionStrategyFactory::chooseStrategy(*it1,*it2);
strategy->processCollision(*(*it1),*(*it2));
}
}
}
}
};
Alternatively you may want to opt for static polymorphism, which also works without RTTI, but needs all types known at compile time. The basic pattern is the so called CRTP.
That should look as follows
class GameObject {
public:
// Put all the common attributes here
const Point& position() const;
const Area& area() const;
void move(const Vector& value);
};
template<class Derived>
class GameObjectBase : public GameObject {
public:
void processCollision(GameObject obj) {
static_cast<Derived*>(this)->processCollisionImpl(obj);
}
};
class SomeGameObject1 : public GameObjectBase<SomeGameObject1 > {
public:
// SomeGameObject1's version of processCollisionImpl()
void processCollisionImpl(GameObject obj) {
}
};
class SomeGameObject2 : public GameObjectBase<SomeGameObject2 > {
public:
// SomeGameObject2's version of processCollisionImpl()
void processCollisionImpl(GameObject obj) {
}
};
But this would unnecessarily complicate the design, and I doubt it will provide any benefits for your use case.