FacundoGFlores
FacundoGFlores

Reputation: 8118

Passing const object by reference issue

Suppose we have the following code:

#include <iostream>

class Person{
public:
    Person(int age);
    int get_a();
private:
    int a;
};

Person::Person(int age)
{
    a = age;
}

int Person::get_a()
{
    return a;
}

void Show_Age(Person P)
{
    std::cout<<P.get_a()<<std::endl;
}

int main() {

    Person P(10);
    Show_Age(P);
    return 0;
}

Now suppose we have a heavy object, we should pass Person by reference, so we proceed:

void Show_Age(Person &P)
{
    std::cout<<P.get_a()<<std::endl;
}

There isn't a problem, but a good observation is P should be const, we try with it:

void Show_Age(const Person &P)
{
    std::cout<<P.get_a()<<std::endl;
}

A compiler failure:

error: passing ‘const Person’ as ‘this’ argument of ‘int Person::get_a()’ discards qualifiers [-fpermissive]

How to solve it?

Upvotes: 3

Views: 5819

Answers (3)

Const correct-ness is viral, and you should start from the inner out (i.e. each class should mark the member functions that don't modify the object as const, allowing callers to use them on const objects (or references to const objects).

Upvotes: 1

Some programmer dude
Some programmer dude

Reputation: 409216

You have to mark Person::get_a as being constant as well:

class Person
{
    // ...

    int get_a() const;

    // ...
};

This tells the compiler that get_a does not modify the object.

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726669

You should mark get_a const in order for this to compile:

class Person{
public:
    Person(int age);
    int get_a() const;
private:
    int a;
};

int Person::get_a() const
{
    return a;
}

Doing so tells the compiler that the member function does not modify the state of the object, making it compatible with const pointers and references.

Upvotes: 12

Related Questions