0

I have a queue that contains Objects of class Event.

std::priority_queue<Event> events;

But Event is just a superclass of actual events. Lets assume we have following classes:

class Event{
   public:
     void Action(){
       std::cout<<"do nothing"<<std::endl;
     }
};

class XEvent : public Event{
   public:
     void Action(){ 
           std::cout<<"do x"<<std::endl;
     }

class YEvent : public Event{
   public:
     void Action(){
            std::cout<<"do y"<<std::endl;
     }
};

and in the main function:

int main(){
  std::vector<Event> events;
  events.push_back(XEvent x);
  events.push_back(YEvent y);
  Event e = events[0];
  e.Action();
}

I want e.Action to behave according to overridden version. (i.e "do x").

But instead the output gives me "do nothing". Any suggestion?

p.s. Im actually looking for a way to do this without using pointers

Jarod42
  • 203,559
  • 14
  • 181
  • 302

3 Answers3

0

Inserting into the vector copies the element. The target type is always Event, given as parameter to the template, so this changes the type.

Suggestions:

  • Use a std::function instead. These may be exactly the thing you are searching for to process events.
  • Use a (smart) pointer type instead, so you can store polymorphic elements.
  • Use a smart union/variant type instead, e.g. Boost.Any or Boost.Variant (not sure if either of them are standardized by now).
Ulrich Eckhardt
  • 16,572
  • 3
  • 28
  • 55
0
class Event{
   public:
     virtual void Action(){
       std::cout<<"do nothing"<<std::endl;
     }
};

use virtual function as above but you created a object that from class Event may be you should create a pointer;

int main(){
  std::vector<Event> events;
  events.push_back(XEvent x);
  events.push_back(YEvent y);
  XEvent xe = events[0];
  Event* e = &xe;
  e->Action();
}

or implement cast a objrct.

CMLDMR
  • 334
  • 2
  • 12
0

use smart pointer shared pointer ,try fallowing code :

#include<iostream>
#include<vector>
#include <memory>

class Event{
   public:
     virtual void Action(){
       std::cout<<"do nothing"<<std::endl;
     }
};

class XEvent : public Event{
   public:
     void Action(){ 
           std::cout<<"do x"<<std::endl;
     }
};

class YEvent : public Event{
   public:
     void Action(){
            std::cout<<"do y"<<std::endl;
     }
};
int main(){
  std::vector<std::shared_ptr<Event>> events;
  events.push_back(std::make_shared<XEvent>());
  events.push_back(std::make_shared<YEvent>());
  std::shared_ptr<Event> e = events[0];
  e->Action();
  return 0;
}
Venkata Naidu M
  • 351
  • 1
  • 6