Reputation: 109
class test {
public:
int& n;
test(int& n) : n(n) {}
};
int main() {
test* ptr = ptr(3); // something like this and 3
// should be a variable as pointed out in the comments
}
Can you initialise a pointer and the object that it points to in one line?
Upvotes: 0
Views: 565
Reputation: 75062
Yes.
class test {
public:
int& n;
test(int& n) : n(n) {}
};
int main() {
int value = 3;
test obj(value), *ptr = &obj;
}
Note that int& n
cannot accept literal like 3
.
Another choice is using new
to create an object on the heap.
class test {
public:
int& n;
test(int& n) : n(n) {}
};
int main() {
int value = 3;
test *ptr = new test(value); // create an object
delete ptr; // delete the object
}
Upvotes: 3