Suppose I have the class
class A {
protected:
int x,y;
double z,w;
public:
void foo();
void bar();
void baz();
};
defined and used in my code and the code of others. Now, I want to write some library which could very well operate on A's, but it's actually more general, and would be able to operate on:
class B {
protected:
int y;
double z;
public:
void bar();
};
and I do want my library to be general, so I define a B class and that's what its APIs take.
I would like to be able to tell the compiler - not in the definition of A which I no longer control, but elsewhere, probably in the definition of B:
Look, please try to think of
Bas a superclass ofA. Thus, in particular, lay it out in memory so that if I reinterpret anA*as aB*, my code expectingB*s would work. And please then actually acceptA*as aB*(andA&as aB&etc.).
In C++ we can do this the other way, i.e. if B is the class we don't control we can perform a "subclass a known class" operation with class A : public B { ... }; and I know C++ doesn't have the opposite mechanism - "superclass a known class A by a new class B". My question is - what's the closest achievable approximation of this mechanism?
Notes:
- This is all strictly compile-time, not run-time.
- There can be no changes whatsoever to
class A. I can only modify the definition ofBand code that knows about bothAandB. Other people will still use classA, and so will I if I want my code to interact with theirs. - This should preferably be "scalable" to multiple superclasses. So maybe I also have
class C { protected: int x; double w; public: void baz(); }which should also behave like a superclass ofA.