livefree75
livefree75

Reputation: 763

Using a non-const object for a const parameter

Perhaps I don't understand the purpose of const in class methods.

Let's say I want to implement a container storing objects of type Foo, but my container promises not to alter any of the Foo objects themselves.

struct Foo
{
    int faz;
    Foo() : faz(0) {}
};

class FooContainer
{
    public:
        FooContainer() : _foos(), _numFoos(0) {}

        void addFoo(const Foo* foo)
        {
            _foos[_numFoos] = foo;
            _numFoos++;
        }

    private:
        const Foo* _foos[10];
        int        _numFoos;
};

int main()
{

    FooContainer fc;
    Foo foo;

    fc.addFoo(&foo);

    return 0;
}

This works fine until I want to grab a Foo out of the container and do something to it. Let's say I add a method to FooContainer:

Foo* getFoo(int index) const
{
    return _foos[index];
}

I get an error saying that I'm trying to convert a const Foo* to a Foo*, which I guess is true because of the return.

So then I put a const in front of it:

const Foo* getFoo(int index) const
{
    return _foos[index];
}

Great, that works. Now, try to get the Foo and do something with it in main():

Foo* foo2 = fc.getFoo(0);

Now I get the same error, converting from a const Foo* to a Foo*. Again, I agree. But of course if I put a const in front of my foo2, I can't change the contents of foo2.

const Foo* foo2 = fc.getFoo(0);
foo2->faz = 3;   // error: assignment of member 'Foo::faz' in read-only object

So, how do I tell my users I ain't gonna change their precious objects inside my container?

I tried making _foos a non-const, but keeping the const on the addFoo(const Foo* foo), but still got an invalid conversion from const Foo* to Foo*.

Upvotes: 0

Views: 53

Answers (1)

Caleth
Caleth

Reputation: 62704

So, how do I tell my users I ain't gonna change their precious objects inside my container?

You don't, and shouldn't. Your container delegates the changing of their precious objects to someone else, so it shouldn't make a promise it doesn't intend to keep.

Upvotes: 2

Related Questions