Returning polymorphic classes from functions

Started by
3 comments, last by loufoque 14 years, 10 months ago
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?
Advertisement
Hmm... do you want to get a Component* from the container and use it as a Component, or do you want to get the Component* and then know whether it is a Graphic/Sound/etc.?

Wielder of the Sacred Wands
[Work - ArenaNet] [Epoch Language] [Scribblings]

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.
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.)
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?

This topic is closed to new replies.

Advertisement