-1

I have one more question about decoration of c++ classes. With decorators I change virtual int get() function. But in NPC class I also call the get() function to get some values for calculation. Is there a way to call Elite::get() inside NPC. I want to get 100 and not 10. Thank you.

class AbstractNPC {
public:
    virtual int get() = 0;
};

class NPC: public AbstractNPC {
public:
    NPC() { }
    int get(){ return 10; }
    calc(){ int i = get(); }
};

class NPCDecorator: public AbstractNPC {
private:
    AbstractNPC * npc;
public:
    NPCDecorator(AbstractNPC *n) { npc = n; }
    int get() { npc->get(); }
};

class Elite: public NPCDecorator {
public:
    Elite(AbstractNPC *n): NPCDecorator(n) { }
    int get() { return 100; }
};

Or is there a better way? Maybe the use of function pointers?

Findus
  • 303
  • 1
  • 4
  • 17

1 Answers1

1

You can just use inheritance:

class Elite: public NPC {
public:
    int get() { return 100; }
};

See it online!


get() method is polymorphic. This means compiler will know whether it should call Elite::get or NPC::get, no matter where you call it. You have to be careful about using virtual methods in constructors or destructors, but otherwise it should work just right.

Yksisarvinen
  • 18,008
  • 2
  • 24
  • 52
  • Thank you. Elite is a Decorator which can be set dynamically by runtime, so I think I have to give up the concept of decorations in this example. – Findus Mar 30 '20 at 14:51
  • Inheritance is usually more [simple and stupid](https://en.wikipedia.org/wiki/KISS_principle) than any design pattern. If you don't have any additional constraints, it's probably good - you can easily use `Elite` in place of `NPC`, you don't need boilerplate code. If you have additional constraints (like you need to call `get()` from within constructor), then you need to think of something else. – Yksisarvinen Mar 30 '20 at 15:13