What's the closest thing in C++ to retroactively defining a superclass of a defined class?

Viewed 2489

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 B as a superclass of A. Thus, in particular, lay it out in memory so that if I reinterpret an A* as a B*, my code expecting B*s would work. And please then actually accept A* as a B* (and A& as a B& 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 of B and code that knows about both A and B. Other people will still use class A, 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 of A.
5 Answers
Related