2

I have the following two classes:

class Image
{
public:
    Image(int size) { _size = size; };
    ~Image();

private:
    int _size;
};


class Renderer
{
public:
    Renderer(int size = 10) { _image = {size}; };
    ~Renderer();
private:
    Image _image;

};

On compilation I get: "no appropriate default constructor available". If I add Image(); the error message goes away.

So my question is, why is the empty constructor necessary? Under which circumstances will it get called?

BoshWash
  • 5,320
  • 4
  • 30
  • 50
  • 1
    Make the constructor of the Renderer class as, Renderer(int size = 10) : _image(Image(size)) {}.. Otherwise, it first tries to create an instance of _image, then you initialize it again. – phoad Mar 15 '15 at 18:27

2 Answers2

3

Because in the constructor of Renderer the Image member must first be constructed, before your constructor body is entered. In your Renderer constructor body you assign to the member, you don't construct it.

If you do it like this, the error disappears without having to provide a default constructor for Image:

Renderer(int size=10): _image(size) { }
emvee
  • 4,371
  • 23
  • 23
1

You are creating a member in the Rendered class "Image _image"...it is not being passed any parameters while being created. To deal with this kind of parameter-less object creation a default constructor is required

Aditya Sanghi
  • 289
  • 1
  • 3
  • 18