Nafai said:
I am going to give a more detailed example:
// I don't type the constructors.
class Event {
private:
int time;
EventType kind;
public:
enum EventType { Event1, Event2,...,Emergency,Crime};
int when() {return time; }
EventType what() { return kind; }
Event is meant to be used as a base class and does not have a virtual
destructor nor virtual functions. What kind of base class is that?
}
class Emergency : public Event {
private:
int area;
public:
int where() {return area;}
};
class Crime : public Event {
private:
string person;
int aCrime;.
public:
string who() { return person; }
int whatHeDid() { return aCrime; }
};
void doSomethingWithEvents(Event* pE)
{
switch(pE->kind) {
case Event::Emergency : callAmbulance(pE->where(),pE->when());
break;
case Event::Crime: blame(pE->who(),pE->whatHeDid(),pE->when());
break;
case Event::Event1 : doSomethingRelatedToEvent1(pE->when());
break;
...
}
}
That is not recommended. You seem not to understand the use of
polymorphism and public inheritance.
Public inheritance has many uses, but in your case, it is a simple case of
interface<->behavior. The base class specifies an interface (with [pure]
virtual functions) and derived classes specify the behavior.
class Event
{
public:
virtual ~Event();
virtual void process() = 0; // that's the
// interface
};
class Emergency : public Event
{
private:
void call_ambulance();
public:
virtual void process() // that's a behavior
{
call_ambulance();
}
};
class Crime : public Event
{
private:
void blame();
public:
virtual void process()
{
blame(); // that's another behavior
}
};
typedef std::sector<Event*> Events;
void f(Events &events)
{
for (Events::iterator itor=events.begin();
itor!=events.end();
++itor)
{
Event *e = *itor;
e->process(); // calls the correct
// process()
}
}
Jonathan