0

I have a class Foo which looks like this

class Foo
{
public:
    void set_bar(int val)
    {
        _bar = val;
    }

protected:
    int _bar;
};

which is inherited by class Baz which is declared as follows:

class Baz
    : public Foo
{
public:
    void set_baz(int val)
    {
        _baz = val;
    }

protected:
    int _baz;
};

and then i have a Factory class which contains a member variable of type Baz.

class Factory
{
protected:
    Baz _baz;
public:
    const Baz& get_baz() const 
    {
        return _baz;
    }
};

If I used Factory like this:

Factory f;
f.get_baz().set_bar(1);

It throws this error C2662: 'Foo::set_bar' : cannot convert 'this' pointer from 'const Baz' to 'Foo &'

SimpleButPerfect
  • 1,529
  • 2
  • 11
  • 20

4 Answers4

1

The object returned by get_baz is constant, you cannot modify its contents.

adamax
  • 3,835
  • 2
  • 19
  • 21
1

You need to provide a non-const version of Factory::get_baz that returns a non-const reference to Baz:

class Factory
{
protected:
    Baz _baz;
public:
    const Baz& get_baz() const 
    {
        return _baz;
    }

    Baz& get_baz()
    {
        return _baz;
    }
};

When using a const Factory, the const version of get_baz will get invoked, otherwise the non-const version of get_baz will get invoked.

You should also refrain from using leading underscores in your names. See What are the rules about using an underscore in a C++ identifier?.

Community
  • 1
  • 1
Emile Cormier
  • 28,391
  • 15
  • 94
  • 122
0

After calling get_baz you are getting constant object and constant object can call only constant function.

Arunmu
  • 6,837
  • 1
  • 24
  • 46
0

You can only change the value if you return a non-const reference to your object.

If you return a non-const reference, why not just make the member public? You'll get the same effect...

Bo Persson
  • 90,663
  • 31
  • 146
  • 203