tags:

views:

67

answers:

2

i have something like this

class A {  
    virtual void doBla(A *a) = 0;
};

class B : public A {
    virtual void doBla(B *b) { // do stuff ;};
};

and i want to do something like

A* a = new B();
B* b = new B();
a->doBla(b);

or: all children of A are supposed to have a method doBla which takes a parameter of the type of the child. Hope you get my problem and hope someone can help me or convince me that this is bad style :)

edit: added virtual to the methods

+1  A: 

You cannot overload functions across base/child classes, and doBla member function of class A must be public if you want to call it from outside:

class A {
  public:
    virtual void doBla(A *a) = 0;
};

class B : public A {
    virtual void doBla(A *a) { /*do stuff*/ }
};

Edit: Note that the declaration of doBla function is similar in A and B classes.

PC2st
@PC2st: isn't it automatically public?
Dirk
@Dirk: class's member functions are private (default) and struct's member functions are public (default).
PC2st
+1  A: 

This is impossible as it stands - a doesn't have a doBla(B* b) function, so when you try to call it on the a instance the compiler can't guarantee in any way that function actually exists, and it doesn't know how to look it up. That's an error or ten.

What you might be looking for is double dispatch.

class A {
public:
    virtual void doBla(A* a) { a->doBla_impl(this); }
private:
    virtual void doBla_impl(A* a);
    virtual void doBla_impl(B* b);
    // etc
};

class B : public A {
public:
    virtual void doBla(A* a) { a->doBla_impl(this); }
private:
    virtual void doBla_impl(A* a);
    virtual void doBla_impl(B* b);
    // etc
};

The trouble with this is that you have to know all the derived types in the base class, which is not always possible or feasible.

DeadMG