Search code examples
c++conversion-operatorupcasting

Acceptable programming practice - conversion and upcasting


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.


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).