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?
First, your member initialization list in A
's converting constructor is wrong. a(a)
should be a(_a)
instead.
Second, A
has a user-defined constructor, so its compiler-generated default constructor is implicitly delete
'd.
Thus, B::a
can't be default-constructed, so B
's compiler-generated default constructor is also implicitly delete
'd.
Thus, b1
in main()
can't be default-constructed, either.
If you want A
to be default-constructible, you need to either:
class A
{
public:
int a = 0;
A() {}; // or: A() = default; // <-- HERE
A(int _a) : a(_a) {}
};
class A
{
public:
int a = 0;
A(int _a = 0) : a(_a) {} // <-- HERE
};
Otherwise, you will have to add a default constructor to B
to construct B::a
with a value:
class B
{
public:
A a;
B() : a(0) {} // <-- HERE
void test()
{
A a1(6);
a = a1;
}
};