开发者

C++ assignment operators question about inheritance

开发者 https://www.devze.com 2023-02-28 13:06 出处:网络
I have two classes - base class A and derived class B - and I write this A obj; B obj2; obj = obj2; What would actually happen if I have yet to overide any assigment operators? Would this just copy

I have two classes - base class A and derived class B - and I write this

A obj;  
B obj2;  
obj = obj2;  

What would actually happen if I have yet to overide any assigment operators? Would this just copy the A part of obj2 into obj? Is this even proper, or a error that the compiler just excuses? Does a IS_A relationship permit this statement to execute? Any help is greatly appre开发者_JS百科ciated.


class Base
{
    //Members       
};

class Derived1:public Base
{
    //Members
};

class Derived2:private Base
{
    //Members 
};


int main()
{
    Base obj1;
    Derived1 obj2;
    Derived2 obj3;

    obj1 = obj2;   //Allowed Since Public Inheritance 
    obj1 = obj3;   //Not Allowed, Compiler generates error
}

When obj1 = obj2 only those members of the Derived Class obj2 that are inherited from Base Class get copied in to obj1, rest of the members of Derived Class get sliced off. This is simply because Base class obj1 is not aware of members of Derived class. This phenomemon is called Object Slicing.

If the class have pointer member variables which need allocation on Heap, then obj1 = obj2 creates a Shallow Copy, which means the pointer member variable inside obj1 and obj2 will now point to the same heap memory. So What happens if obj2 is reclaimed by the OS and obj1 is still in use? Disaster! So shallow copies should be avoided by overloading = operatorand making a Deep copy of objects.


This is certainly allowed. It will assign the A subobject of obj2 to obj.

Due to the IS-A relationship, it is pretty much impossible to prevent this at compile time without also preventing assignment from an instance of A.


It would shallow copy the "A" part of the obj2.

It is perfectly OK from the language standpoint.

If it is OK for your app, that depends on many factors, but that is why you can overload the assignment operator.


overload your assignment operator. and in mplementation B part thts in A part will be assigned... no compiler error will be generated till u try to assign values of B that exist in A


A::operator=(const A& value);

will be executed. obj1 implicitly cast (static_cast) to const A&.

So your obj=obj1; is equivalent to

obj = static_cast<const A&>(obj1);

Obviously implicitly generated assignment will assign every non-static member of A.

To deny this use private/protected inheritance. By using public inheritance you claim that all objects of type B may be legitimately used as objects of type A in every possible way.

You also may explicitly declare

A& A::operator=( const B& value );

Or you also may define

A& A::operator=( const A& value );

to behave in polymorphic way.

0

精彩评论

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