Reputation: 19855
I am not sure is that legal or not in C++:
class Image
{
Image(int w, int h) // constructor
{
...
}
Image GetSpecialImage()
{
Image rVal(10,10);
return rVal;
}
}
Do I need to use another middle level init()
method to do this in C++? If yes, can you please show me how?
EDIT:
Eventhough you say it's fine, it does not really do what I want to do... Let me give you some more code:
class Image
{
float* data;
int w;
int h;
Image(int w, int h) // constructor
{
this->w = w;
this->h = h;
data = (float*) malloc ( w * h * sizeof(float) );
}
Image GetSpecialImage()
{
Image rVal(this->w,this->h);
for(i=0;i<this->w * this->h;i++)
{
rVal.data[i] = this->data[i] + 1;
}
return rVal;
}
}
int main()
{
Image temp(100, 100);
Image result = temp.GetSpecialImage();
cout<<result.data[0];
return 0;
}
Is there anything wrong with this part?
Upvotes: 0
Views: 303
Reputation: 1513
While there's nothing wrong with this code (well, except for returning a local, which is a no-no), I guess what you're looking for is a static constructor pattern. Like so:
class Image{
public:
static Image* GetSpecialImage(){
return new Image(10,10);
}
};
//and call it so
Image *i = Image::GetSpecialImage();
Upvotes: 0
Reputation: 1498
Yes, you can do this. I would just do this though
Image GetSpecialImage()
{
return Image(10,10);
}
Upvotes: 1
Reputation: 54363
As Seth said, that is legal.
Something you could change to make it work even better is to make GetSpecialImage
a static function. A static function defined in a class is a class function instead of an object function. That means you don't need an object in order to call it.
It would then be called like this: Image special = Image::GetSpecialImage();
Upvotes: 5