Law
Law

Reputation: 482

Add things to the Update method of parent class

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 ?

Upvotes: 0

Views: 778

Answers (2)

Chris Drew
Chris Drew

Reputation: 15334

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(); 
    }
};

Upvotes: 0

Chris
Chris

Reputation: 1244

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
    }
};

Upvotes: 5

Related Questions