0

I have two classes:

class Object {
public: void Update();
};

class Cube : public Object {
void Update();
};

I want a Update() method that does everything I tell it, then does everything the Update from the parent class does. Can I do that ?

Law
  • 483
  • 1
  • 5
  • 9

2 Answers2

5

Maybe you want to change your design a little bit. Something like this could do what you want:

class Object {
public: 
    void Update(
        // invoke method from derived
        onUpdate();

        // do stuff in base
    );

protected:
    virtual void onUpdate() = 0;
};

class Cube : public Object {
    void onUpdate() {
        // do stuff in derived
    }
};
Chris
  • 1,226
  • 1
  • 12
  • 26
  • What does the `= 0` in `virtual void onUpdate() = 0;` do ? – Law Jan 16 '15 at 21:21
  • 1
    It means the method is "pure virtual". Adding pure virtual methods to a class make it an abstract class, meaning it cannot be instantiated. Have a look here for example: http://stackoverflow.com/questions/1306778/c-virtual-pure-virtual-explained – Chris Jan 16 '15 at 21:25
  • If there is nothing unclear anymore, please accept the answer again. – Chris Jan 16 '15 at 21:35
0

You can simply write Object::update() in Cube's update function but it is generally considered bad practice to redefine an inherited non-virtual function so I suggest you also make update virtual

class Object {
  public:
    virtual void update(){ /* ... */ }
};

class Cube : public Object {
  public:
    void update() override {
        // ...
        Object::update(); 
    }
};
Chris Drew
  • 14,926
  • 3
  • 34
  • 54