vendredi 23 février 2018

Updating class variable or calling class function from member variable is giving runtime error

I am trying to implement update which will update to all the listerner classes I am using class variable to count number of listeners. MyClass 's are extending listener to listen from the updater class

I am getting runtime error when I am trying to update class variable with class function from member function. Please refer below code and help me out sorting this problem

 #define MAX_LISTNERS 10
class Listner{
public: 
virtual void onUpdate() = 0;
};
class Updater {
    Listner* ptrListner[MAX_LISTNERS];
    static int count;
    public: 
     static void updateCount(){
        count++;
    }
    void registerListner(Listner* ptrListner){
        this->ptrListner[count] = ptrListner;
        this->updateCount(); //---> Runtime Error
    }
    void updateToListner(){
        for(int i=0;i<=count;i++){
        this->ptrListner[i]->onUpdate();
        }
    }
};
 int  Updater::count = 0;
class MyClass: public Listner{
    public:
     void onUpdate(){
        cout<<"update from MyClass";
     }
};  
class MyClass2: public Listner{
    public:
     void onUpdate(){
        cout<<"update from MyClass2";
     }};
int main() {
    MyClass* obj = new MyClass();
    MyClass2* obj2 = new MyClass2();
    Updater obj_updater;
    obj_updater.registerListner(dynamic_cast<Listner*>(obj));
    obj_updater.registerListner(dynamic_cast<Listner*>(obj2));
    obj_updater.updateToListner();
}

Aucun commentaire:

Enregistrer un commentaire