Sign in to follow this  
Niddles

Returning polymorphic classes from functions

Recommended Posts

Okay, I have a question about how I should return a polymorphic class from a function. I have a class hierarchy like this:
class Component
{
  ...
};
class Graphic : public Component
{
  void linkTexture(Texture);
  ...
};
class Sound : public Component
{
  ...
};

//And so on with more components that each have their own thing to do

Alright, I have a container of Component* in a system class. I want to return a Component* from a getComponent function, to be able to access the component's methods outside of the system class. Will it work, and is it kosher to have one:
Component* System::getComponent(...);
That will return whichever component I ask for, and it will know whether it is a Graphic, a sound, a physics entity so I can access the distinct methods from each class?

Share this post


Link to post
Share on other sites
I want to use it as a Graphic/Sound/etc. I think I figured out that I have to have separate accessor functions that I can cast the Component* to Graphics* or Sound*. I am starting to think this is bad design, so I'm sitting back and rethinking things a bit. I just can't come up with a nice component based, modular design to base things off.

Share this post


Link to post
Share on other sites
Zen: At the United Nations, all the delegates are simply people.

(Putting things in the same container is effectively declaring that you don't care about their differences. The point of polymorphism is to not have to think about how the various derived classes implement things; as a consequence of that, you are supposed to also not think about their derived-specific functionality. If you need that functionality, don't forget about it in the first place; i.e., if you need to play() Sounds, then keep them in a Sound container instead of a Component container.)

Share this post


Link to post
Share on other sites
Quote:
Alright, I have a container of Component* in a system class. I want to return a Component* from a getComponent function, to be able to access the component's methods outside of the system class. Will it work, and is it kosher to have one:

Component* System::getComponent(...);


That will return whichever component I ask for, and it will know whether it is a Graphic, a sound, a physics entity so I can access the distinct methods from each class?

I don't get it.
If you know the actual type, why aren't you returning it?

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this