I have these three codes:
#pragma once
class Rect
{
private:
int m_Thing;
public:
Rect(int thing)
{
m_Thing = thing;
}
void create(int thing)
{
m_Thing = thing;
}
};
#pragma once
#include "Rect.h"
class Brick
{
private:
Rect floatRect;
public:
Brick()
{
floatRect.create(28);
}
};
#include "mre.h"
#include <iostream>
int main()
{
Brick brick;
}
For some reason, I get an error that says I need a default constructor. I make one, and then I get an unresolved external symbol error on the Rect object. That's where I'm stuck. How can I instantiate it?
When you call an default constructor of a class, all of its members are default constructed unless specified some other way. If we wanted to write what happens explicitly in the call of Brick()
, it would look like this.
Brick() : floatRect()
{
floatRect.create(28);
}
Here we can see that in the member initializer list it attempts to call the default constructor of Rect
, which is implicitly deleted because you have a user-defined constructor. If you want to create Rect
, you can do the following.
Brick() : floatRect(28)
{
}
The member initialized field is purposely for initializing or passing arguments to the constructors of members.