user997112
user997112

Reputation: 30615

Declare object on heap and then passing it by reference?

If I was to declare an object on the heap like so:

X* x = new X();
func(?);

void func(X& x);

How can I pass x in to func() so that func() can receive a reference to x (and not a pointer)?

Upvotes: 2

Views: 1453

Answers (2)

David Heffernan
David Heffernan

Reputation: 613013

De-reference the pointer and pass it like this:

func(*x);

Your function must be passed something of type X. The fact that the object is passed by reference is passed doesn't change how you call it. Since x has type X* you need to de-reference x in order to get something of type X.

To illustrate, suppose you had

void func1(X& x);
void func2(const X& x);
void func3(X x);
void func4(const X x);

For each case you would call the functions in identical fashion.

Upvotes: 3

Caesar
Caesar

Reputation: 9843

You have to dereference it like so:func(*x)

Upvotes: 4

Related Questions