Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why type qualifiers ignored on function return type only in case of primitives?

Tags:

c++

While trying to remove warnings from c++ project i failed to understand why first function returning int gives warning "warning: type qualifiers ignored on function return type" but second function returning std::string doesn't give this warning ?

   //first function
    const int getX()
    {
        int x =9;
        return x;
    }
   //second function
    const std::string getTemp()
    {
        std::string test = "Test..";
        return test;
    }
like image 398
PapaDiHatti Avatar asked Nov 19 '16 04:11

PapaDiHatti


1 Answers

const on a primitive type has no effect for a return value, because you can't modify an rvalue of a primitive type.

getX() = 5; // error, even if getX() returns a non-const int.

For a class type however, const can make a difference:

std::string s = getTemp().append("extra");
   // error if getTemp() returns a `const std::string`, but valid
   // if getTemp() returns a non-const `std::string`.
like image 165
Vaughn Cato Avatar answered Nov 14 '22 21:11

Vaughn Cato