Reputation: 9
Suppose I have a base class B, derived class D, derived derived class DD. How can I get the instance of the immediate parent to my current object?
e.g.
DD dd;
if (condition )
dd->myfunction();
else
d = getcurrentparent(); // this should give the current parent, here D d;
Edit:
Ok I am adding my scenario.
Its like an Menu. And each menu is different class.
main menu - base class sub menu - derived class sub sub menu - derived derived class.
Now when I am traversing in the sub sub menu, I need to know the immediate parent of the current obj (like going back from sub sub menu to sub menu)
Upvotes: 0
Views: 336
Reputation: 815
Try something like this,
class D : public B
{
virtual const char * GetParent()
{
return "B";
}
// other stuff....
}
class DD : public D
{
virtual const char * GetParent()
{
return "D";
}
// other stuff....
}
I Hope this is what you want. Why do you need such a thing? are you creating something like an object registry with a hierarchy or something similar?
--EDIT--
D * d = ⅆ
or if you really want,
create a copy function which copies DD objects to D objects.
But what i guess is that you are not asking your question correctly.
p.s. sorry that i read the question wrongly the first time.
--EDIT--
Ok, What you need is Composite Design Pattern. Its not very complex as the UML diagram shows. Once you implement it, its really easy to code your other stuff. When talking about design patterns, I like the book "Design Patterns for Dummies". It explains the design patterns very nicely and it has explained the Composite Design pattern very well. If you need help in it put a comment asking. but first try to do it yourself. :) enjoy. Wikipedia Link : http://en.wikipedia.org/wiki/Composite_pattern
--EDIT--
Composite DP is like this,
assuming your scenario is a very simple menu on the console, i would do it like this,
Leaf
==> MenuItem
classComposite
==> Menu
class +operation()
==> Select()
function of the both classes. This function should be virtual and overridden in the Menu
class and MenuItem
class to display/expand and select item respectively.Menu
class will have functions to GoBack()
to parent menuUpvotes: 1
Reputation: 18368
Not a good idea. You can do what was suggested above but that's not a good design choice. Besides, what parent do you want in case of multiple inheritance(or multiple interfaces)?
Upvotes: 1
Reputation: 40633
If you have DD dd;
, you can always get a reference to any of its base classes just by assigning to a reference:
DD dd;
D& d = dd;
I'm not sure why you would want to do this though, as a derived object can do everything that the base object can do (and more).
Upvotes: 2