Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Protected / Public overloads

I have a class like this :

class Foo
{
public:
    Foo()
    {
        for(int i = 0; i < 10; ++i)
            v.push_back(i);
    };
    const vector<double>& V() const {return v;};
protected:
    vector<double>& V() {return v;};
private:
    vector<double> v;
};

And then a piece of code like this :

Foo foo;
for(int i = 0; i < (int) foo.V().size(); ++i)
    cout << foo.V().at(i) << endl;

However, the latter raises a compilation error saying the V() call is a protected method while i am just trying to read from it, not modify it.

I have tried the following (but without success).

Foo foo;
const vector<double>& test = foo.V();
for(int i = 0; i < (int) test.size(); ++i)
    cout << test.at(i) << endl;

Many thanks for your help.

=====

Thank you all for the explanations and solutions ! It's greatly appreciated !

like image 624
foo Avatar asked May 26 '11 07:05

foo


2 Answers

It is not possible to overload on return value. Non-const method will be used when the object is non-const. It is possible to guide the compiler by:

const vector<double>& test = const_cast<Foo const&>(foo).V();

Or possibly nicer solution is to have the constant method have different name (eg.: ConstV). Or you can just add this new method and leave the current method there. This approach is used in C++0x standard. For example constant methods cbegin() and cend() have been added to standard containers.

like image 56
Juraj Blaho Avatar answered Sep 24 '22 11:09

Juraj Blaho


Overload resolution does not take member accessibility into account, so an ideal overload candidate is chosen and then member accessibility is checked to see if the call is legal.

The realistic workaround is:

Foo foo;
Foo const& foo_alias = foo;
for (std::size_t i = 0; i != foo_alias.V().size(); ++i)
    cout << foo_alias.V().at(i) << endl;
like image 23
ildjarn Avatar answered Sep 25 '22 11:09

ildjarn