简体   繁体   中英

Is it necessary to overload the assignment operator and the copy constructor for a class A which has a data member of another class B?

I have a class List , which has as a member of pointer of type Vector (my own class). For this class I have overloaded the assignment operator and redefined the copy-constructor.

The problem is that I am not sure if a have to do the same thing for a new class, which has a member of type List (not dynamically allocated).

class List {
    Vector *l;
    int len;
    // assignment operator and copy-constructor defined here
}

class Graf_Neorientat : public Graf {
    List L;
    ...
};

The member variable L in your Graf_Neorientat class can be assigned and copied just the same way as if it was a normal variable in your program. So you don't need to do write again that code in Graf_Neorientat to be able to copy L when Graf_Neorientat is copied.

Now, probably what you wanted to ask instead is if you need to do something "extra" in Graf_Neorientat to make it also copyable (and copy L when doing so).

Assuming Graf is copyable (or ignoring Graf ), the answer is no. If your List class is copyable, then your Graf_Neorientat will be copyable. The compiler will define implicitly the assignment operator and copy constructor for you, which will call in turn the List ones to copy the L member appropriately.

Of course, you can disable copyability yourself in Graf_Neorientat if you want in several ways, and you can also define a different assignment operator and copy constructor if you wish to do something else (rare). But, as given in your example, Graf_Neorientat will do what you expect.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM