Click to See Complete Forum and Search --> : Inheritance: Ensure call of base fucntion from derived class


GNiewerth
February 28th, 2008, 04:05 AM
Hi,

I´ve got two classes: Base and Derived. Base offers some virtual (non pure virtual method) that are overwritten by Derived. Is it possible to ensure that Derived calls Base function from the overwritten Derived function?

Here´s an example:


class Base
{
public:
Base()
{
}

virtual Base()
{
}

virtual void func1()
{
// do some stuff
}

virtual void func2()
{
// do some more stuff
}
};

class Derived1 : public Base
{
public:
Derived1()
{
}

void func1()
{
// OK, calls Base func
Base::func1();

// do some Derived specific stuff
}

void func2()
{
// oops, forgot to call Base::func2()
// do some Derived specific stuff
}
};

laserlight
February 28th, 2008, 04:10 AM
Perhaps this will work:
class Base
{
public:
Base()
{
}

virtual ~Base() {}

void func1()
{
// do some stuff
func1_();
}

void func2()
{
// do some more stuff
func2_();
}

protected:
virtual void func1_()
{
// do nothing
}

virtual void func2_()
{
// do nothing
}
};

class Derived1 : public Base
{
public:
Derived1()
{
}

protected:
void func1_()
{
// do some Derived specific stuff
}

void func2_()
{
// do some Derived specific stuff
}
};
The idea is that Base provide hooks for the Derived class to implement.

GNiewerth
February 28th, 2008, 04:36 AM
Great suggestion, I think it will fit my needs.
Thank you

PS:
Unfortunately I have no reputation to spread at the moment.

code_carnage
February 28th, 2008, 05:24 AM
Same here.. What do I have to do to get reputation to spread?

laserlight
February 28th, 2008, 05:30 AM
Look out for good posts by various other people and add to their reputation :)

GNiewerth
February 29th, 2008, 07:30 AM
Hi again,

I gave some thought to your suggestion, laserlight, and find it very useful for flat hierachies with only one level of inheritance. How do I implement it for two or more levels, is it possible at all?

laserlight
February 29th, 2008, 07:34 AM
I gave some thought to your suggestion, laserlight, and find it very useful for flat hierachies with only one level of inheritance. How do I implement it for two or more levels, is it possible at all?
EDIT:
Okay, I did some experimentation, and I think that one cannot really prevent the problem elegantly. Perhaps the best you can do is to provide yet another hook function, and specify that subclasses should implement that instead of the original hook function from the base class.