I'm currently making c project but this error is bothering me for long time and i cannot figure out why this doesn't work. I was searching about this error but still i don't understand it.
Thanks in advance.
#include <iostream>
using namespace std;
class A
{
public:
int a = 0;
A(int _a) : a(a) {}
};
class B
{
public:
A a;
void test()
{
A a1(6);
a = a1;
}
};
int main()
{
B b1;
b1.test();
return 0;
}
I tried to initialized value in constructor in class and this worked but what if i don't want to do this?
CodePudding user response:
A
doesn't have a default constructor so it cannot be default constructed.
A class object must be fully initialized before entering the body of the constructor which means that in B
you need to initialize a
(either with data member init or with constructor list initialization).
If for whatever reason you want to delay the initialization of a
you have a few options. Depending on the semantics of it you could make it std::optional<A> a
or std::unique_ptr<A>
.