开发者

Acceptable programming practice - conversion and upcasting

开发者 https://www.devze.com 2023-04-10 16:24 出处:网络
Is the following acceptable programming practice: class TestA { prote开发者_开发技巧cted: int A; public:

Is the following acceptable programming practice:

class TestA
{
    prote开发者_开发技巧cted:
        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.


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消