user3337808
user3337808

Reputation: 11

What does invalid initialization of reference mean?

My code is like this

std::string & Product::getDescription() const { return &description; }

I've tried it all different ways with description and *description and nothing works, but when I take off the reference part of the return type it works fine. The thing is though that we're supposed to use &. I'm really confused as to why nothing works. Also earlier in the project there was the code:

void Product::setDescription(const std::string &newUnits) const { units = newUnits; }

With units being declared as a global public variable. The exact error it gives me is:

error: invalid initialization of reference of type ‘std::string& {aka std::basic_string&}’ from expression of type ‘const string {aka const std::basic_string}’

Upvotes: 0

Views: 535

Answers (4)

4pie0
4pie0

Reputation: 29724

when you initialize reference you don't use & operator on variable:

int i = 0;
int& j = i;  // now j is reference for i

similarly in the function, return variable without &:

std::string& Product::getDescription() const {
    return description;
} // equivalent for std::string& returned = description;

In addition you are allowed to return only const reference from const function. So this should be:

const std::string& Product::getDescription() const {
    return description;
}

or

std::string& Product::getDescription() {
    return description;
}

Upvotes: 2

lrineau
lrineau

Reputation: 6274

Your method Product::getDescription() const should return a reference to a const object, because the method is const. What is more, &description is pointer to the string, because in that context & is the address-of operator. You do not initialize a reference from a pointer. Use the following:

const std::string & Product::getDescription() const { return description; }

Upvotes: 0

Mike Seymour
Mike Seymour

Reputation: 254471

That's a const member function, meaning that the object that it's called on (and its members) are const within the function. You can't return a non-const reference to a member.

You can return a const reference from a const function:

const std::string & Product::getDescription() const;

and a non-const reference from a non-const function

std::string & Product::getDescription();

Assuming description has type std::string, you would return the reference with just return description;, with no &.

The set function can't be const, since it modifies the object.

Upvotes: 0

Chad
Chad

Reputation: 19032

When returning a reference you don't use the address-of operator:

class Product
{
   std::string description;
   const std::string& get_description() const { return description; }
   void set_description(const std::string& desc) { description = desc; }
};

Upvotes: 0

Related Questions