Question

Is the following acceptable programming practice:

class TestA
{
    protected:
        int A;

    public:
        TestA(){A = 10;}
        TestA &operator=(const TestA &ItemCopy)
        {
            A = ItemCopy.A;
            printf("A is: %d!\n",A);
            return *this;
        }
};

class TestB : public TestA
{
    protected:
        int B;

    public:
        TestB(){A = 20; B = 30;}
        operator const TestA&(){ return *this; } //Note returns reference, upcasts implicitly.
};

int main()
{
    TestA Test;
    TestB Test2;

    Test = Test2; //Calls Test2's (AKA TestB's) conversion operator
    return 0;
}

What reason is it acceptable/unacceptable?

(Please avoid making the obvious suggestion about making a TestB assignment operator in TestA - this is a question on whether upcasting and/or conversion operators should or should not be used in this manner).

I also encourage that feedback is left in the comments for question upvote/downvotes so I can improve my questions in future.

Was it helpful?

Solution

No conversion operator is needed here, a const TestA& is perfectly capable of binding to an instance of a derived class (because inheritance is public).

OTHER TIPS

The operator you've written is actually not needed at all. The language does that for you automatically when you use public inheritance. You could completely remove the operator and it will still function the same. And upcasting is typically fine, that's how you use inheritance by assigning a parent pointer/reference to a derived instance.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top