Reputation: 13
I am in the process of creating a scene graph for a 2D game engine. I've created a base class called Node, which is derived by Sprite, which in turn is derived by Player. Each class has the virtual function update()
. I want to call every update()
in each class. I don't know if this is possible (Except using base::update()
, but that's a little messy with many derived classes).
The following code provides a little insight into the current structure of my project.
#include <iostream>
class Base
{
public:
virtual void print()
{
std::cout << "Hello from Base ";
}
};
class Derived : public Base
{
public:
virtual void print()
{
std::cout << "and Derived!" << std::endl;
}
};
int main()
{
Derived foo = Derived();
foo.print(); // Obviously outputs only "and Derived!"
}
While the above does exactly as expected, my desired output is actually "Hello from Base and Derived!".
I know I can put Base::print()
at the top of Derived::print()
, but I am looking for a method to that's a little cleaner with many derived classes on top of each other.
I'm a little new to C++ as a language, and I couldn't find info on this subject. I'm open to complete changing my approach if it's not in the style of proper polymorphism. I'd rather do things right than botching it to just get this affect.
Upvotes: 1
Views: 178
Reputation: 93
Sometimes C++ does something you are not expecting.
My advice is to use a feature of the C language that it has to support.
In this case, I used union
to achieve the programmatic effect you are seeking:
#include <iostream>
class Base
{
public:
virtual void print()
{
std::cout << "Hello from Base ";
}
};
class Derived : public Base
{
public:
virtual void print()
{
std::cout << "and Derived!" << std::endl;
}
};
int main(void);
int main()
{
Base foo;
Derived bar;
union foobar {Base *b; Derived *d;} fb;
fb.b = &foo; fb.b->print();
fb.d = &bar; fb.d->print();
return 0;
}
CODE LINK: http://ideone.com/JdU8T6
Upvotes: 0
Reputation: 1
I know I can put
Base::print()
at the top ofDerived::print()
, but I am looking for a method to that's a little cleaner with many derived classes on top of each other.
You have to do that explicitely if you want it, That's the whole point of overriding with polymorphism.
class Derived : public Base
{
public:
virtual void print()
{
Base::print();
std::cout << "and Derived!" << std::endl;
}
};
As you're mentioning graphs (tree like structures), you should have a look at the Visitor Pattern.
Upvotes: 2