How can one enforce calling a base class function after derived class constructor?
Posted
by Mike Elkins
on Stack Overflow
See other posts from Stack Overflow
or by Mike Elkins
Published on 2010-04-08T14:17:53Z
Indexed on
2010/04/08
14:23 UTC
Read the original article
Hit count: 199
I'm looking for a clean C++ idiom for the following situation:
class SomeLibraryClass {
public:
SomeLibraryClass() { /* start initialization */ }
void addFoo() { /* we are a collection of foos */ }
void funcToCallAfterAllAddFoos() { /* Making sure this is called is the issue */ }
};
class SomeUserClass : public SomeLibraryClass {
public:
SomeUserClass() {
addFoo();
addFoo();
addFoo(); // SomeUserClass has three foos.
}
};
class SomeUserDerrivedClass : public SomeUserClass {
public:
SomeUserDerrivedClass() {
addFoo(); // This one has four foos.
}
};
So, what I really want is for SomeLibraryClass to enforce the calling of funcToCallAfterAllAddFoos at the end of the construction process. The user can't put it at the end of SomeUserClass::SomeUserClass(), that would mess up SomeUserDerrivedClass. If he puts it at the end of SomeUserDerrivedClass, then it never gets called for SomeUserClass.
To further clarify what I need, imagine that /* start initialization */ acquires a lock, and funcToCallAfterAllAddFoos() releases a lock.
The compiler knows when all the initializations for an object are done, but can I get at that information by some nice trick?
© Stack Overflow or respective owner