c++ inheritance question

Started by
5 comments, last by tjrr3d 17 years, 12 months ago
Say I inherit a class but instead of overriding a function, I want to append on to it. Is there a way to call the parent function first from the child class? example:

class Parent
{
    public:
       Parent();
       ~Parent();

       Update();
};

Parent::Parent(){
}
Parent::~Parent(){
}
Parent::Update(){
  // Update X
}



class Child : public Parent
{
    public:
       Child();
       ~Child();

       Update();
};

Child::Child(){
}
Child::~Child(){
}
Child::Update(){
  // Call parent Update() to update X
  // Now update y
}

Advertisement
void Child::Func(){  Parent::Func();  std::cout << "More stuff" << std::endl;}

enum Bool { True, False, FileNotFound };
You should of course ensure that the parent class has a virtual destructor, and also ensure that any member functions you redefine are virtual too.
is it a rule of thumb that all inherited classes have their respective destructors virtualized? even if they are non-existant or empty?
sig
Quote:Original post by pcxmac
is it a rule of thumb that all inherited classes have their respective destructors virtualized? even if they are non-existant or empty?
With public inheritance yes (99.5% of cases). With private and protected inheritance it depends.
Quote:Original post by tjrr3d
Say I inherit a class but instead of overriding a function, I want to append on to it. Is there a way to call the parent function first from the child class?

example:
*** Source Snippet Removed ***
As an alternative to what hplus0603 said, a "template method" may be used:
class Parent{    public:       Parent();       virtual ~Parent();       void Update() { ...code...; doUpdate(); }    private:       virtual void doUpdate()=0;};

And now Child-class just needs to do whatever it wants in doUpdate, and not worry about what else the parent-class's Update is doing. When using the class, you'll actually be calling Update (a public method) instead of doUpdate (a virtual private method).
That last one will work great for what I need Anonymous Poster. Thanks guys.

This topic is closed to new replies.

Advertisement