Reputation: 1
I am trying to initialise class object (which has constant members) with certain values and certain address. I understand that this is because members are constant but I need them to be constant. I tried to find solution but with no success.
So the question is: is there some "easy" way to do it?
class ints{
public:
const int a;
const int b;
ints(int a, int b);
};
ints::ints(int a, int b) :
a{a},
b{b}
{}
int main() {
auto ptr = (ints*)malloc(sizeof(ints));
ints values{1, 2};
// all wrong
// *ptr = ints copy{values};
// &values = ptr;
// *ptr = values;
std::cout << ptr->a; //ptr->a should be equal to 1
}
Upvotes: 0
Views: 68
Reputation: 238351
You can create an object at a specific address using placement-new:
extern void* some_address;
int main()
{
ints* ptr = new(some_address) ints{1, 2};
std::cout << ptr->a;
}
Upvotes: 1