I am on a micro controller (which means I can only have static memory allocation) and I am trying to work with inheritance.....
Suppose I have a abstract class Image and an abstract class Font. An instance of Font can return an Image based off of the char given in a function like so:
Font* mf;
Image* image = mf->GetImage("a");
Now the real issue is I have no idea what to do for the GetImage Function.
The problem is this: in c++ for you to have a member of an abstract class you have to use it as a pointer. So my dilemma is that I have a Font which wants to create a new Image and then return it.
If it returns a pointer to its newly created Image you are returning a reference to a temporary object:
Image* FontImpl::GetImage(char c){
return &ImageImpl(c); //This object is destroyed once this function exits
}
And then if I return I try to return an actual type like this:
Image FontImpl::GetImage(char c){
return ImageImpl(c); //Cannot cast from ImageImpl to Image
}
So is there an idiom or something for this kind of static memory problem?
EDIT: This is what I am doing as a temporary (possibly permanent) fix...let me know what you think:
I have a new class called UnionBase which is templated. The idea behind using this class is it can be any of the Derived types which you put into the template....You would use it like so:
UnionBase<Image,ImageImpl1,ImageImpl2> myImage;
myImage = ImageImpl1(); //I can assign to it any type in the templates
myImage->ImageMethod(); //I can use all of the methods of the base class
Using this idiom I would then do this:
void FontImpl::GetImage(char c, UnionBase& b){
b = //Set it to somthing
}
The UnionBase type allocates the size of its largest member so all of them can fit... if you want me to post code for it I can.
FontImpl::GetImagewould allocate an ImageImpl object from the pool and return a pointer to it. The ImageImpl destructor would return the object to the pool.'a'identical for a given font?charor returns an image with 0 width and height....No each font gives (or could give) a different image for an'a'