overload method not getting called in cast operator overload [duplicate]

By : Sepehr
Source: Stackoverflow.com
Question!

I have a base class that includes a virtual method and a cast operator:

class Base {
public:
    Base() {}
    operator int() const { return getInt(); }
protected:
    virtual int getInt() const { return 0; }
}

Then I have two derived classes that override the virtual method:

class Derived1 {
public:
    Derived1() : Base() {}
protected:
    virtual int getInt() const override { return 1; }
}

class Derived2 {
public:
    Derived2() : Base() {}
protected:
    virtual int getInt() const override { return 2; }
}

Then I have a helper function:

Base helper(const bool flag) {
    if (flag)
        return Derived1();
    else
        return Derived2();
}

The intention of that helper function is to be used like:

int one = helper(true); // I expect "one" to be 1
int two = helper(false); // I expect "two" to be 2

But both one and two contain 0. I have no idea how to resolve this. Is the cast operator getting called before the Derived classes are fully constructed? My environment is VS2013.


Suggested fix (in my case, after answers)

I ended up turning the helper function into a class which stores Deriveds as members and returning a reference to them (which I believe is actually a better design since on each [] call a Derived does not get constructed / allocated):

class Helper {
public:
    Helper();
    const Base& get(const bool flag) const {
        if (flag)
            return mDerived1;
        else
            return mDerived2;
    }
private:
    Derived1    mDerived1;
    Derived2    mDerived2;
}

Side note

Accepted answer suggests that the gist of the question is thinking about everything as in references (like Python) and that is true. This issue came up as a part of a bigger system design which allows access to results returning from a SQLite database with a Python like syntax in C++. Chaining square brackets like: mData[0][1].

By : Sepehr


This video can help you solving your question :)
By: admin