class A
{
public:
A() { }
~A() { }
protected:
virtualvoid initChild();
void initA()
{
// some work...
initChild();
// some work...
}
};
class B : public A
{
public:
B() {
// ...initialize some B stuff here...
// want to force an initA() call before exiting B()'s constructor
}
~B() { }
virtualvoid initChild() { }
};
Is there a design pattern I can use to ensure that the leaf child class calls initA() before exiting the constructor? In this case, on line 20?
The problem with initA() is, it needs to do some work before and after calling initChild(), a virtual method. If I put all this in A's constructor, it will fail because the vtables aren't set up properly yet. However, the current way I'm doing it, I have to remember to put the call to initA() on line 20 before exiting the constructor for every leaf subclass or I'm in trouble.
I'm looking for a design pattern that can handle this. TIA.
In class B A's constructor *must* be called before B's constructor executes. Here is how you need to do it:
1 2 3 4 5 6 7 8 9 10 11 12
class B : public A
{
public:
B()
: A() // call A's constructor.
{
// ...initialize some B stuff here...
// want to force an initA() call before exiting B()'s constructor
}
~B() { }
virtualvoid initChild() { }
};
If you don't specify it the compiler will call A's default constructor regardless (if A has a default constructor). If A does not have a default constructor you will get a compiler error if you fail to call one of A's constructors from B's constructor as shown in the example.
EDIT: Actually I misread your requirements, so my example doesn't exactly solve your issue.
Galik, thx for the reply. Yes, I know about that default constructor.
Let me rephrase my problem. I need to call
initA1(); initChild(); initA2();
in that sequence, where initChild() is a virtual function and initA1() and initA2() are well-defined inside A. How do I code this dependency into the classes so this sequence of initializers is called every time?