gornvix
gornvix

Reputation: 3384

What's the correct syntax for passing this class to a reference?

Say I have two classes:

class Foo
{
public:
    int x;
};

class Bar
{
public:
    Foo *foo;
};

An instance as follows:

Bar *bar;
bar = new Bar();

And a function that takes a Foo object by reference:

void func(Foo &foo);

What is the correct way to call this function with the foo in bar as in bar->foo ?

Upvotes: 2

Views: 84

Answers (2)

Toby Speight
Toby Speight

Reputation: 30928

bar->foo is a pointer to a foo. We just need to dereference that pointer:

Foo& f = *bar->foo;
func(f);

Or (all in one)

func(*bar->foo);

Upvotes: 0

Vittorio Romeo
Vittorio Romeo

Reputation: 93354

The correct syntax is:

func(*(bar->foo));

Upvotes: 9

Related Questions