Reputation: 1097
I have two object, call the A
and B
e.g
class A {
private:
int x;
int y;
public:
A();
A(int x, int y);
void setX(int);
void setY(int);
};
class B {
private:
const A a1;
public:
B();
B(int x, int y) {
//my problem is here
A a(x, y);
this->a1 = a;
};
};
If B
is initialised with parameters, I want to have a1
initialised with parameters as well which B
is initialised with, hence A(int x, int y)
.
I don't want a1
initialised in heap.
I currently getting this error
no operator "=" matches these operands -- operand types are: const Brain = Brain
From the answer below by @songyuanyao
B::B(int x, int y) : a1(x, y){};
it works but I have a different problem now due to my lack of knowledge for const
. When I call setX
and setY
from A(int x, int y)
like this
A::A(int x, int y) {
setX(x);
setY(y);
}
void A::setX(int x) {
this->x = x;
}
void A::setY(int y) {
this->y = y;
}
it doesn't seem to change the x
and y
values/attributes of class A
.
Upvotes: 1
Views: 36
Reputation: 172924
You should initialize the const
data member with member initializer list. As const
object, it could be initialized, but can't be assigned; so this->a1 = a;
doesn't work.
For members that cannot be default-initialized, such as members of reference and const-qualified types, member initializers must be specified.
e.g.
B(int x, int y) : a1(x, y) {}
Upvotes: 3