Hi all,
is there a way to obtain dynamic inheritance of objects? I've searched the web a lot, but i couldn't find something clear. Let me explain it with an example:
Let's say we have a class A, which is the base class. Now, we have 2 other classes, B and C which inherit A (i.e. B : A and C : A). Is there a way to define a class which dynamically change its inheritance from B to C and viceversa? Some kind of X which will be inherited by a new class D (i.e. D : X), where X can be B or C. Let me give a simple diagram to make it more clear:
A
/ \
B C
\ /
?
X
|
D
and with code:
B : A
C : A
X (pass check) : B
X (else) : C
D : X
Thanx in advance
ps: it's a bit complicated to tell why do i need this thing, that's why i omit it.
C++ is a strongly typed language. If you inherit class X from both B and C, then you can use dynamic_cast<C> or dynamic_cast<B> to treat it as one of the parent classes. C++ would do this through multiple inheritance.
Thanx for the reply. I know that i can have multiple inheritance but the problem is that i want something like dynamic inheritance because the inherited type must be decided by the constructor. What i mean is, looking also at the previous example i posted, lets say we have class X which may take as parameter type B or C (2 constructors). Now, if we pass B we want, for the base class, to be of type B. The same goes with C.
So, i need something like the following:
class X : public "someFuctionMaybe"
{
various members
};
and one constructor:
X::X("someFuctionMaybe")
{
various initializations
}
When we'll call "new X(type)", depending on "type" the analogous base class will be called. I can't just dynamic_cast the new object (or maybe i misunderstood something) because is the object itself that must choose the inheritance
Is it possible to put as base class "someFuctionMaybe" which will do the dynamic_cast thing?![]()
You would do better to have a separate factory class that returns a pointer of type A that is created as type B or C based on the parameter handed to the factory class.
Ehmm, i'm not sure that i understand what you meanCould you please explain it further?
Thanx
You would have a class/function called factory that returns a pointer to A. It's parameter determines what type it calls with the new operator.
Code:A* factory(std::string type) { if type="A" return new A; if type="B" return new B; if type="C" return new C; ... }
Thanx a lot for the replyI'll try it
There are currently 1 users browsing this thread. (0 members and 1 guests)
Bookmarks