0

There is a simple version of my code :

   class Action:
        {
        int updateOK() {
            std::cout << "" << std::endl;
            return 0;
        }
   }
   class Attack:public Action
        {
        int updateOK() {
            std::cout << "att" << std::endl;
            return 0;
        }
   }
   class Def:public Action
        {
        int updateOK() {
            std::cout << "DEf" << std::endl;
            return 0;
        }
    }

    namespace actions
    {
        const Attack light = Attack();
        const Attack meduim = Attack();
        const Attack heavy = Attack();
        const Block block = Block();
        const Block cancelBlock = Block();
        const std::vector<Action> listAction = { light , meduim, heavy , block, cancelBlock };
    }

    Main.cpp :
    for each (Action action in actions::listAction) {
                action.updateOK();
    }

The issue is that it always calls the parent function in the main.

I have tried virtual functions in many ways but I want to find a solution to the problem without casts.

Is it possible ?

Moran Abadie
  • 29
  • 1
  • 6

2 Answers2

0

what you are trying to do is Object slicing:

It happens when a derived class object is assigned to a base class object, additional attributes of a derived class object are sliced off to form the base class object

Abhishek Chandel
  • 1,294
  • 2
  • 13
  • 19
0

If you don't mind casts you need to:

  • Make parent function virtual for dynamic binding to work
  • if you need to use a generic container you will need to use pointers to base class as objects.

Sample edits:

   class Action:
   {
        virtual int updateOK() {
            std::cout << "" << std::endl;
            return 0;
        }
   };

--- the rest of classes --- 

    namespace actions
    {
        const Action* light = new Attack();
        const Action* meduim = new Attack();
        const Action* heavy = new Attack();
        const Action* block = new Block();
        const Action* cancelBlock = new Block();
        const std::vector<Action*> listAction { light , meduim, heavy , block, cancelBlock };
    }

    Main.cpp :
    for(Action* action : actions::listAction) {
                action->updateOK();
    }
aybassiouny
  • 559
  • 5
  • 14
  • I tried it before but the problem is that it gave me an ` error : cannot convert from 'Action *const ' to 'Action'` – Moran Abadie Apr 12 '16 at 13:40