ctor-, dtor-like behavoir on functions

Hey all,

Lets take a look at this code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Base
{
public:
    Base() { /* initialization here */ }

    void DoWork() { /* work here */ }
};

class Derived : public Base
{
public:
    Derived() { /* additional initialization here */ }

    void DoWork() { /* additional work here */ }
};


I know that the Base constructor will be called first, before the Derivedctor, when you create a Derived object. I find that a useful situation, you onl y have to make some additional code to make Derived work. But, I want that functionality for normal functions too. Like, when you have a Derived object and you call its void DoWork() function like this:
1
2
Derived derived;
derived.DoWork();

that DoWork from Base will be called first, and DoWork from Derived right after it. Then I only have to add functionality, instead of calling the Base version of DoWork within DoWork of Derived.

Is that possible in C++?

Thanks.
No, you need to explicitly call the base class version from the derived class function.
1
2
3
4
5
6
7
8
9
10
11
12
class Derived : public Base
{
public:
    Derived() { /* additional initialization here */ }

    void DoWork()
    {
        Base::DoWork(); // do the base class part

        // Now do the additional stuff
    }
};

You might want to check out the Template pattern. It might be applicable for your application.
There's also this approach:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Base
{
public:
    void DoWork()
    {
        /* work here */
        Child_DoWork();
    }

private:
    virtual void Child_DoWork() { }
};

class Derived : public Base
{
private:
    virtual void Child_DoWork()
    {
        /* additional work here */
    }
};
Last edited on
Topic archived. No new replies allowed.