I am trying to write a method that loads data from a file. The filename is stored as a data member of a derived class, and I want the loading function to be in the virtual base class (the loading is the same for all of the derived classes, so I don't want to rewrite it for every one of them). Is there a way the base class can have access to the derived data members without knowing what the derived class is? I will be calling this on an array of RenderObjects (the base class). Thanks for looking!!
Virtual Base class RenderObject's method:
void RenderObject::loadSounds();
{
// Retrieve filename from derived class
std::ifstream infile;
infile.open(filename);
std::string temp;
while(!infile.eof())
{
infile >> temp;
Mix_Chunk* sound = Mix_LoadWAV(file);
sounds.push_back(sound); // sounds is an array of Mix_Chunk pointers
} // in the RenderObject class
}
Derived classes could be player, enemy, etc.
Sorry if this is a trivial question, I found lots of stuff about getting base class stuff from derived classes, but not the other way around...
I'm also not sure if this is the best way to do this, just an idea I had, so if you think the whole scheme is dumb let me know! :)
class Parent
{
void LoadSounds()
{
// load things specific to 'Parent' here
DoLoadSounds();
}
protected:
virtualvoid DoLoadSounds() {}
};
class Child : public Parent
{
protected:
virtualvoid DoLoadSounds()
{
// load things specific to 'Child' here
}
};
Now if you call LoadSounds in the parent class it will load parent specific stuff, then call the virtual DoLoadSounds so child specific stuff can be loaded.
Is something like this what you're looking for?
From the looks of your code snippit, you might want to consider using a resource manager. Objects typically shouldn't own resources like sound effects. Consider if you have multiple copies of the same object active at once. You'll load the sound effect multiple times for each of them -- very wasteful.