INB
INB

Reputation: 175

Returning a const reference in C++

In the following code, _myFoo is a const reference to an object of type Foo.

struct Foo
{
};

const Foo& _myFoo();

const Foo& GetMyFoo()
{
    return _myFoo;
}

When I try to compile it, I get the following error:

error: invalid initialization of reference of type 'const Foo&' 
from expression of type 'const Foo& (*)()'

What am I doing wrong? Is there some way of returning _myFoo via a function call?

Upvotes: 0

Views: 103

Answers (1)

Borgleader
Borgleader

Reputation: 15916

_myFoo is not a variable, it's a function returning a const Foo& and that takes no parameters. Either change the declaration of _myFoo (and possibly put it inside struct Foo), or do return _myFoo(); and give _myFoo a definition.

Note though that if myFoo is indeed supposed to be a function, you should not prefix it with an underscore as I believe function names beginning with underscores are reserved.

Upvotes: 5

Related Questions