Diamond inheritance with a third party library - c++

I have a classic diamond problem like this in C++
A
/ \
B C
\ /
D
I know this would normally be solved by making B and C inherit virtually from A.
But my issue is that classes A and B come from a third party library I can't edit and B's inheritance from A is not marked virtual.
Is there a way to solve this?
Thanks for the help ;-)

An simple way to solve this problem is to introduce an Adapter class. This way, the hierarchy becomes
A
/
B AdapterC
\ /
D
And the code of AdapterC would look like
class AdapterC
{
public:
explicit AdapterC(C c) : c(std::move(c)) {}
operator C& () { return c; } //Maybe this should be explicit too...
/** Interface of C that you want to expose to D, e.g.
int doSomething(double d) { return c.doSomething(d); }
**/
private:
C c;
};
As the saying goes, "All problems in computer science can be solved by another level of indirection, except of course for the problem of too many indirections". Of course, it might be a lot of work to write and maintain this Adapter. Hence, I think people that comment your question are probably right and that you should revisit your design.

Key design issue
If you can't change the inheritance of A in your library to virtual, there is no way to make a diamond with a single A element a the top. The standard explicitly allows for mixing virtual and non-virtual inheritance of the same base class:
10.1/6: for an object c of class type C, a single subobject of type V is shared by every base subobject of c that has a virtual base
class of type V. (...).
10.1/7: A class can have both virtual and non-virtual base classes of a given type.
Example:
namespace mylib { // namesape just to higlight the boundaries of the library
struct Person { // A
static int counter;
int id;
Person() : id(++counter) {}
void whoami() { cout << "I'm "<<id<<endl; }
}; //A
struct Friend: Person {}; //B -> A
int Person::counter=0;
}
struct Employee : virtual mylib::Person {}; // C->A
struct Colleague : Employee, mylib::Friend {}; // D->(B,c)
...
mylib::Friend p1; // ok !
p1.whoami();
Employee p2; // ok !
p2.whoami();
Colleague p3; // Attention: No diamond !
//p3.whoami(); // ouch !! not allowed: no diamond so for which base
// object has the function to be called ?
p3.Employee::whoami(); // first occurrence of A
p3.mylib::Friend::whoami(); // second second occurrence of A
Online demo
Alternative design
As you have no way to intervene in your external library you have to organize things differently. But however you'll do it, it will be sweat and tears.
You could define C (Employee in my example) by using composition of A (Person in my example). The A subobject would either be created or in special cases taken over from another object. You'd need to undertake the effort to replicate A's interface, forwarding the calls to an A subobject.
The general idea would look like:
class Employee {
mylib::Person *a;
bool owna;
protected:
Employee (mylib::Person& x) : a(&x), owna(false) { } // use existing A
public:
Employee () : a(new mylib::Person), owna(true) { } // create A subobject
~Employee () { if (owna) delete a; }
void whoami() { a->whoami(); } // A - fowarding
};
If you do this, you could then define D with multiple inheritance, with a trick in the constructor:
struct Colleague : mylib::Friend, Employee {
Colleague () : mylib::Friend(), Employee(*static_cast<Person*>(this)) {};
using Friend::whoami;
};
The only issue would then the ambiguity of the member functions of A interface (that have been provided in C as explained above). You therefore have to tell with a using clause that for A, you go via B and not via C.
In final, you could use this:
Employee p2;
p2.whoami();
Colleague p3; // Artifical diamond !
p3.whoami(); // YES !!
p3.Employee::whoami(); // first occurence of A
p3.mylib::Friend::whoami(); // second second occurence of A
// all whoami refer to the same A !!!
It works nicely: Online demo
Conclusion
So yes, it's possible to solve this, but it's very tricky. As I said: it will be sweat and tears.
For instance, you have no problem to convert a Colleague to a Person. But for Employee, you'd need to provide conversion operators. You have to implement the rule of 3/5 in Employee And you have to take care of everything that could go wrong (failed allocation, etc...). It will not be a piece of cake.
So it's really worth to reconsider your design, as Lightness Races in Orbit suggested in the comments :-)

Related

Avoiding unrequired function declarations/definitions when using inheritance in C++

After a long time of C-style procedural coding, I am just beginning to 'get' OOP. So I suspect there may be standard way of dealing with the situation I am facing. I have an application with the class hierarchy shown below:
#include <iostream>
using namespace std;
class A {
public:
virtual int intf() { return 0;} // Only needed by B
virtual double df() {return 0.0;} // Only needed by C
};
class B : public A {
int intf() {return 2;}
// B objects have no use for df()
};
class C : public B {
double df() {return 3.14;}
// C objects have no use for intf()
};
int main(){
// Main needs to instantiate both B and C.
B b;
C c;
A* pa2b = &b;
A* pa2c = &c;
cout << pa2b->intf() << endl;
cout << pa2b->df() << endl;
cout << pa2c->intf() << endl;
cout << pa2c->df() << endl;
return 0;
}
Now this program compiles and runs fine. However, I have question about its design. Class A is the common interface and does not need to be instantiated. Class B and C need to be. Regarding the functions: intf() is needed by B but not C, and df() is needed by C but not B. If I make intf() {df()} pure virtual in A, then there is no reasonable definition of df() {intf()} for B {C}.
Edit: B and C share some data members and also some member functions other than f(). I have not shown it my stripped down code.
Finally, as is standard, my application needs to access both B and C through a pointer to A. So my question is: Is there a way to 'clean up' this design so that unrequired/empty member function definitions (such as I have done in declaration/definition of A) can be eliminated? There is a clear "IS-A" relationship between the classes. So even though I share every newbie's thrill about inheritance, I dont feel I have stretched my design just so I could use inheritance.
Background in case it helps: I am implementing a regression suite. Class A implements functions and matrices common to every regression (such as dependent and independent variables). Class B is logistic regression with two classes ('0' and '1') and defines cost functions, and training algorithm for two-class logistic regression. Class C is multi-class logistic regression. It extends class B by training for multiple classes using the "one-vs-all" algorithm. So in a sense C is a binary logistic regression if you think of your class of interest as positive examples and all others as negative examples. Then you do it for every class to implement multi-class regression. The functions (intf and df) in question return the output. In case of logistic regression, the return value is a vector, while for multiclass regression, it is a matrix. And, as stated above, B and C dont have any use for each others' return functions. Except that I cant seem to be able to eliminate redundant definitions in A (the regression class).
Thanks for your help.
Look at the Liskov Substitution Principle (http://en.wikipedia.org/wiki/Liskov_substitution_principle). It states that subclasses must fulfill the same contract as the superclass. In your example, neither subclass does this. The "Is-A" relationship is not enough to justify inheritance.
One option would be to use a single template method something like this:
template <typename T>
class A<T> {
T getValue();
}
class B : A<int> {
int getValue();
}
class C: A<double> {
double getValue();
}
this would allow the contract to be fulfilled by both subclasses while allowing the return type of the method to vary based on the subclass definition.
If you want to learn more object oriented programming "best practices", google "Robert Martin SOLID"
You touched one of the most controversial point of OOP: the is-a == derivation pattern, resulting int the "god object" anti-pattern, since everything is ultimately a child-of-god, with god knowing every method of everyone and having an "answer" (read "default implementation") for everything.
"Is-a" is not enough to justify inheritance, where no replace-ability exist, but in real world no object is really fully replaceable with another, otherwise it will not be different.
You are in the "land of nowhere" where the substitution principle doesn't work well, but -at the same time- virtual functions look the best tool to implement dynamic dispatch.
The only thing you can do come to a compromise, and sacrifice one of the two.
As far the situation looks like, since B and C have nothing in common (no shared useful methods), simply don't let those method to originate from A.
If you have something to "share" is probably a runtime mechanism to discover the type of B or C before entering B related specific code or C related specific code.
This is typically done with a common base having a runtime-type indicator to switch upon, or just a virtual function (typically the destructor) to let dynamic_cast to be able to work.
class A
{
public:
virtual ~A() {}
template<class T>
T* is() { return dynamic_cast<T*>(this); }
};
class B: public A
{
public:
int intf() { return 2; }
};
class C: public A
{
public:
double df() { return 3.14; }
};
int main()
{
using namespace std;
B b;
C c;
A* ba = &b;
A* ca = &c;
B* pb = ba->is<B>();
if(pb) cout << pb->intf() << endl;
C* pc = ca->is<C>();
if(pc) cout << pc->df() << endl;
}

How to Call Function of one class on the object of another class?

How can I call one method in one class over using another class ?
I have ;
class A {
public :
foo ( ) ;
};
class B {
public :
bar ( ) ;
};
in main :
A data ; // I am creating instance of class A
data . bar ( ) ; // but, I am calling a method of another class
// how can I do that ?
Note : I could not find a appropriate title. If you have one, feel free to share or edit
Unless the two classes are related(through inheritance) You cannot do that.
A member functions performs some action on the instance of the class to which it belongs.
You created an object of class A so you can only call member functions of A through it.
Grinding an Apple and hoping to get a mango shake, won't really happen right.
Use public inheritance:
class B {
public:
void bar();
};
class A : public B
{ };
int main() {
A a;
a.bar();
}
I think if you want use .bar() on A object A must inherit by B.
It is not clear what you want data.bar() to do.
bar() as no access to A's data, so bar() cannot have anything to do with the variable data. So, I would argue, that data.bar() is unnecessary, you are aiming for just bar().
Presumably, if bar() is just a function, you can declare it static and call B.data()
The other option is that you wanted inheritance which some other people have already written about. Be careful with inheritance, and make sure you inherit A from B only if you there is a is-a relationship, and it satisfies the Liskov Principle. Don't inherit from B just because you have to call bar().
If you want to use B, you can have a instance of B inside A. Read about prefering composition over inheritance
As everyone said in their answers.
Its a bad idea and not possible.
You can only use tricks that no one really knows how its gonna behave.
You can get the pointer of an object A and cast it to be poiter of B.
Again the only use of that is to show other what not to do.
A a;
B* b = (B*)&a;
b->bar();
I think you should read 1 or 2 c plus plus book(s) and get a fair idea what classes are about and what purpose they are meant to serve.
Some suggestions: The c++ programing by Bjarne Stroustrup or Thinking in c++ by Bruce Eckel or search over net for tutorials.
You can use a function pointer. The only way to make it not static is to use templates.
class A
{
public:
void setBar(void (*B::func)(void)) { bar = func; };
void callBar() { bar(); };
private:
void(*B::bar)(void);
};
class B
{
public:
static void bar() { printf("you called bar!"); };
};
int main() {
A a;
a.setBar(B::bar);
a.callBar();
}
You can also declare class B as a friend of class A.
I believe the syntax for it is:
class A {
public:
foo();
friend class B;
};
class B {
public:
bar();
};
But with this, I believe you can only use functions/variables from A inside B functions.
Inheritance will probably be your better approach to it.
Although this question is strange !, but here are some solutions
Using inheritance
class A: public B
Type cast
A data;
((B*)&data)->bar();
Or reinterpret cast
B* b = reinterpret_cast <B*> (&data);
b->bar();
If bar() use any member variables of B, then the result is not predictable.

Accessing a protected member of a superclass-typed member object - an elegant solution

First off, I know I can not do it, and I think it's not a duplicate questions (this and this questions deal with the same problem, but they only want an explanation of why it does not work).
So, I have a similar concept of classes and inheritance and I would, somehow, elegantly, want to do something that's forbidden. Here's a very simple code snippet that reflects what I want to do:
#include <iostream>
class A{
protected:
int var;
std::vector <double> heavyVar;
public:
A() {var=1;}
virtual ~A() {}
virtual void func() {
std::cout << "Default behavior" << this->var << std::endl;
}
// somewhere along the way, heavyVar is filled with a lot of stuff
};
class B: public A{
protected:
A* myA;
public:
B(A &a) : A() {
this->myA = &a;
this->var = this->myA->var;
// copy some simple data, e.g. flags
// but don't copy a heavy vector variable
}
virtual ~B() {}
virtual void func() {
this->myA->func();
std::cout << "This class is a decorator interface only" << std::endl;
}
};
class C: public B{
private:
int lotsOfCalc(const std::vector <double> &hv){
// do some calculations with the vector contents
}
public:
C(A &a) : B(a) {
// the actual decorator
}
virtual ~C() {}
virtual void func() {
B::func(); // base functionality
int heavyCalc = lotsOfCalc(this->myA->heavyVar); // illegal
// here, I actually access a heavy object (not int), and thus
// would not like to copy it
std::cout << "Expanded functionality " << heavyCalc << std::endl;
}
};
int main(void){
A a;
B b(a);
C c(a);
a.func();
b.func();
c.func();
return 0;
}
The reason for doing this is that I'm actually trying to implement a Decorator Pattern (class B has the myA inner variable that I want to decorate), but I would also like to use some of the protected members of class A while doing the "decorated" calculations (in class B and all of it's subclasses). Hence, this example is not a proper example of a decorator (not even a simple one). In the example, I only focused on demonstrating the problematic functionality (what I want to use but I can't). Not even all the classes/interfaces needed to implement a Decorator pattern are used in this example (I don't have an abstract base class interface, inherited by concrete base class instances as well as an abstract decorator intreface, to be used as a superclass for concrete decorators). I only mention Decorators for the context (the reason I want a A* pointer).
In this particular case, I don't see much sense in making (my equivalent of) int var public (or even, writing a publicly accessible getter) for two reasons:
the more obvious one, I do not want the users to actually use the information directly (I have some functions that return the information relevant to and/or written in my protected variables, but not the variable value itself)
the protected variable in my case is much more heavy to copy than an int (it's a 2D std::vector of doubles), and copying it in to the instance of a derived class would be unnecessarily time- and memory-consuming
Right now, I have two different ways of making my code do what I want it to do, but I don't like neither of them, and I'm searching for a C++ concept that was actually intended for doing something of this sort (I can't be the first person to desire this behavior).
What I have so far and why I don't like it:
1. declaring all the (relevant) inherited classes friends to the base class:
class A{
....
friend class B;
friend class C;
};
I don't like this solution because it would force me to modify my base class every time I write a new subclass class, and this is exactly what I'm trying to avoid. (I want to use only the 'A' interface in the main modules of the system.)
2. casting the A* pointer into a pointer of the inherited class and working with that
void B::func(){
B *uglyHack = static_cast<B*>(myA);
std::cout << uglyHack->var + 1 << std::endl;
}
The variable name is pretty suggestive towards my feelings of using this approach, but this is the one I am using right now. Since I designed this classes, I know how to be careful and to use only the stuff that is actually implemented in class A while treating it as a class B. But, if somebody else continues the work on my project, he might not be so familiar with the code. Also, casting a variable pointer in to something that I am very well aware that it is not just feels pure evil to me.
I am trying to keep this projects' code as nice and cleanly designed as possible, so if anybody has any suggestions towards a solution that does not require the modification of a base class every now and then or usage of evil concepts, I would very much appreciate it.
I do believe that you might want to reconsider the design, but a solution to the specific question of how can I access the member? could be:
class A{
protected:
int var;
static int& varAccessor( A& a ) {
return a.var;
}
};
And then in the derived type call the protected accessor passing the member object by reference:
varAccessor( this->myA ) = 5;
Now, if you are thinking on the decorator pattern, I don't think this is the way to go.
The source of the confusion is that most people don't realize that a type has two separate interfaces, the public interface towards users and the virtual interface for implementation providers (i.e. derived types) as in many cases functions are both public and virtual (i.e. the language allows binding of the two semantically different interfaces). In the Decorator pattern you use the base interface to provide an implementation. Inheritance is there so that the derived type can provide the operation for the user by means of some actual work (decoration) and then forwarding the work to the actual object. The inheritance relationship is not there for you to access the implementation object in any way through protected elements, and that in itself is dangerous. If you are passed an object of a derived type that has stricter invariants regarding that protected member (i.e. for objects of type X, var must be an odd number), the approach you are taking would let a decorator (of sorts) break the invariants of that X type that should just be decorated.
I can't find any examples of the decorator pattern being used in this way. It looks like in C++ it's used to decorate and then delegate back to the decoratee's public abstract interface and not accessing non-public members from it.
In fact, I don't see in your example decoration happening. You've just changed the behavior in the child class which indicates to me you just want plain inheritance (consider that if you use your B to decorate another B the effects don't end up chaining like it would in a normal decoration).
I think I found a nice way to do what I want in the inheritance structure I have.
Firstly, in the base class (the one that is a base for all the other classes, as well as abstract base class interface in the Decorator Pattern), I add a friend class declaration only for the first subclass (the one that would be acting as abstract decorator interface):
class A{
....
friend class B;
};
Then, I add protected access functions in the subclass for all the interesting variables in the base class:
class B : public A{
...
protected:
A *myA;
int getAVar() {return myA->var;}
std::vector <double> &getAHeavyVar {return myA->heavyVar;}
};
And finally, I can access just the things I need from all the classes that inherit class B (the ones that would be concrete decorators) in a controlled manner (as opposed to static_cast<>) through the access function without the need to make all the subclasses of B friends of class A:
class C : public B{
....
public:
virtual void func() {
B::func(); // base functionality
int heavyCalc = lotsOfCalc(this->getAHeavyVar); // legal now!
// here, I actually access a heavy object (not int), and thus
// would not like to copy it
std::cout << "Expanded functionality " << heavyCalc << std::endl;
std::cout << "And also the int: " << this->getAVar << std::endl;
// this time, completely legal
}
};
I was also trying to give only certain functions in the class B a friend access (declaring them as friend functions) but that did not work since I would need to declare the functions inside of class B before the friend declaration in class A. Since in this case class B inherits class A, that would give me circular dependency (forward declaration of class B is not enough for using only friend functions, but it works fine for a friend class declaration).

Is this a design flaw?

Consider two classes
class A{
public:
A(){
}
~A(){
}
};
class AImpl : public A{
public:
AImpl(){
a = new AInternal();
}
AImpl(AInternal *a){
this->_a = a;
}
~AImpl(){
if(a){
delete a;
a = null;
}
}
private:
AInternal *a;
};
I am trying to hide the AInternal's implementation and expose only A's interface. Two things I see here
class A is totally empty.
Hiding is achieved basically through inheritance. I have to actually use downcasting and upcasting from A to AImpl and vice versa.
Is this a good design. Being very inexperienced in designing, I cannot see the pitfalls of it and why it is bad?
You're overcomplicating things by using 3 classes. I think what you're looking for is the pimpl idiom.
I am trying to hide the AInternal's implementation and expose only A's interface.
I think you are trying to do something like factory.
Here is an example:
class IA {
public:
IA() {}
virtual ~IA() {}
virtual void dosth() =0;
};
class Factory {
private:
class A : public IA {
public:
A () {}
virtual ~A() {}
void dosth() { cout << "Hello World"; }
};
public:
Factory () {}
virtual ~Factory() {}
IA*newA() { return new A; }
};
And the usage of Factory class:
Factory f;
IA*a = f.newA();
a->dosth();
return 0;
IMO AInternal makes no sense. Whatever you do there, should be done in AImpl. Otherwise, it's ok to do that in C++.
The code is rather obtuse, so I would be concerned with maintaining it six months down the road.
If you're going to do it this way, then the destructor ~A needs to be virtual.
You seem to be combining two common design features:
1) AInternal is a "pimpl". It provides for better encapsulation, for example if you need to add a new field to AInternal, then the size of AImpl doesn't change. That's fine.
2) A is an base class used to indicate an interface. Since you talk about upcasting and downcasting, I assume you want dynamic polymorphism, meaning that you'll have functions which pass around pointers or references to A, and at runtime the referands will actually be of type AImpl. That's also fine, except that A's destructor should either be virtual and public, or non-virtual and protected.
I see no other design problems with this code. Of course you'll need to actually define the interface A, by adding some pure virtual member functions to it that you implemented in AImpl. Assuming you plan to do that, there's nothing wrong with using an empty base class for the purpose which in Java is served by interfaces (if you know Java). Generally you'd have some kind of factory which creates AImpl objects, and returns them by pointer or reference to A (hence, upcasts them). If the client code is going to create AImpl objects directly then that might also be fine, and in fact you might not need dynamic polymorphism at all. You could instead get into templates.
What I don't see is why you would ever have to downcast (that is, cast an A* to AImpl*). That's usually bad news. So there may be some problems in your design which can only be revealed by showing us more of the definitions of the classes, and the client code which actually uses A and AImpl.

Dependency on Derived class constructor problem

I am working on a legacy framework. Lets say 'A' is the base-class and 'B' is the derived class. Both the classes do some critical framework initialization. FWIW, it uses ACE library heavily.
I have a situation wherein; an instance of 'B' is created. But the ctor of 'A' depends on some initialization that can only be performed from 'B'.
As we know when 'B' is instantiated the ctor for 'A' is invoked before that of 'B'. The virtual mechanism dosen't work from ctors, using static functions is ruled-out (due to static-initialization-order-fiasco).
I considered using the CRTP pattern as follows :-
template<class Derived>
class A {
public:
A(){
static_cast<Derived*>(this)->fun();
}
};
class B : public A<B> {
public:
B() : a(0) {
a = 10;
}
void fun() { std::cout << "Init Function, Variable a = " << a << std::endl; }
private:
int a;
};
But the class members that are initialized in the initializer list have undefined values as they are not yet executed (f.e. 'a' in the above case). In my case there a number of such framework-based initialization variables.
Are there any well-known patterns to handle this situation?
Thanks in advance,
Update:
Based on the idea given by dribeas, i conjured-up a temporary solution to this problem (a full-fledged refactoring does not fit my timelines for now). The following code will demonstrate the same:-
// move all A's dependent data in 'B' to a new class 'C'.
class C {
public:
C() : a(10)
{ }
int getA() { return a; }
private:
int a;
};
// enhance class A's ctor with a pointer to the newly split class
class A {
public:
A(C* cptr)
{
std::cout << "O.K. B's Init Data From C:- " << cptr->getA() <<
std::endl;
}
};
// now modify the actual derived class 'B' as follows
class B : public C, public A {
public:
B()
: A(static_cast<C*>(this))
{ }
};
For some more discussion on the same see this link on c.l.c++.m. There is a nice generic solution given by Konstantin Oznobikhin.
Probably the best thing you can do is refactoring. It does not make sense to have a base class depend on one of its derived types.
I have seen this done before, providing quite some pain to the developers: extend the ACE_Task class to provide a periodic thread that could be extended with concrete functionality and activating the thread from the periodic thread constructor only to find out that while in testing and more often than not it worked, but that in some situations the thread actually started before the most derived object was initialized.
Inheritance is a strong relationship that should be used only when required. If you take a look at the boost thread library (just the docs, no need to enter into detail), or the POCO library you will see that they split the problem in two: thread classes control thread execution and call a method that is passed to them in construction: the thread control is separated from the actual code that will be runned, and the fact that the code to be run is received as an argument to the constructor guarantees that it was constructed before the thread constructor was called.
Maybe you could use the same approach in your own code. Divide the functionality in two, whatever the derived class is doing now should be moved outside of the hierarchy (boost uses functors, POCO uses interfaces, use whatever seems to fit you most). Without a better description of what you are trying to do, I cannot really go into more detail.
Another thing you could try (this is fragile and I would recommend against) is breaking the B class into a C class that is independent of A and a B class that inherits from both, first from C then from A (with HUGE warning comments there). This will guarantee that C will be constructed prior to A. Then make the C subobject an argument of A (through an interface or as a template argument). This will probably be the fastest hack, but not a good one. Once you are willing to modify the code, just do it right.
First, I think your design is bad if the constructor of a base class depends on the something done in the constructor in a derived. It really shouldn't be that way. At the time the constructor of the base class run, the object of the derived class basically doesn't exist.
A solution might be to have a helper object passed from the derived class to the constructor of the base class.
Perhaps Lazy Initialization does it for you. Store a flag in A, wether it's initialized or not. Whenever you call a method, check for the flag. if it's false, initialize A (the ctor of B has been run then) and set the flag to true.
It is a bad design and as already said it is UB. Please consider moving such dependencies to some other method say 'initialize' and call this initialize method from your derived class constructor (or anywhere before you actually need the base class data to be initialized)
Hmm. So, if I'm reading into this correctly, "A" is part of the legacy code, and you're pretty damn sure the right answer to some problem is to use a derived class, B.
It seems to me that the simplest solution might be to make a functional (non-OOP) style static factory function;
static B& B::makeNew(...);
Except that you say you run into static initialization order fiasco? I wouldn't think you would with this kind of setup, since there's no initialization going on.
Alright, looking at the problem more, "C" needs to have some setup done by "B" that "A" needs done, only "A" gets first dibs, because you want to have inheritance. So... fake inheritance, in a way that lets you control construction order...?
class A
{
B* pB;
public:
rtype fakeVirtual(params) { return pB->fakeVirtual(params); }
~A()
{
pB->deleteFromA();
delete pB;
//Deletion stuff
}
protected:
void deleteFromB()
{
//Deletion stuff
pB = NULL;
}
}
class B
{
A* pA;
public:
rtype fakeInheritance(params) {return pA->fakeInheritance(params);}
~B()
{
//deletion stuff
pA->deleteFromB();
}
protected:
friend class A;
void deleteFromA()
{
//deletion stuff
pA = NULL;
}
}
While it's verbose, I think this should safely fake inheritance, and allow you to wait to construct A until after B has done it's thing. It's also encapsulated, so when you can pull A you shouldn't have to change anything other than A and B.
Alternatively, you may also want to take a few steps back and ask yourself; what is the functionality that inheritance gives me that I am trying to use, and how might I accomplish that via other means? For instance, CRTP can be used as an alternative to virtual, and policies an alternative to function inheritance. (I think that's the right phrasing of that). I'm using these ideas above, just dropping the templates b/c I'm only expecting A to template on B and vice versa.