Polymorphism and inheritance...

I can't do the following due to the fact that the Base class doesn't have a function named Hello():
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Base {
  public:
    virtual ~Base (void) {}
};

class Derived :public Base {
  public:
    void Hello () const { std::cout << "Hello World!" << std::endl; }
};

int main (void) {
  Base* b = new Derived;
  b->Hello();
  delete b;
}


I realize that I can add a pure virtual function to the Base class using a prototype that matches the function in the Derived class, or I can use dynamic_cast instead.

I ask because it makes no sense. That would mean that if I created a library, the users of the library would either need to dynamic_cast their way around the issue, or I would need to add a prototype for any function they declared when they inherited from my Derived class or even my Base class, which is obviously impossible.

Thanks for any information you can provide! ^_^

rpgfan
Last edited on
I'm not sure what you really want to do, but to call Hello directly, you either have to add a virtual declaration to the base class, or using dynamic_cast.

You may be interested in something like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <iostream>
class Base;
class Derived;

class Visitor {
  public:
    virtual ~Visitor() {}
    virtual void visit(Base&) {}
    virtual void visit(Derived&) {}
};

class Base {
  public:
    virtual ~Base (void) {}
    virtual void accept(Visitor& v) { v.visit(*this); }
};

class Derived :public Base {
  public:
    virtual void accept(Visitor& v) { v.visit(*this); }
    void Hello () const { std::cout << "Hello World!" << std::endl; }
};

class SayHello : public Visitor {
  public:
    void visit(Base& o) {}
    void visit(Derived& o) { o.Hello(); }
};

int main (void) {
  Base* b = new Derived;
  SayHello h;
  b->accept(h);
  delete b;
}
Topic archived. No new replies allowed.