0

Assuming i have this code:

class A { public: int x; A(){} A(const A& a){} //copy constructor operator= (const A &a){...} }; class B { public: A a; B(){} }; int main() { B b; B c = b; //shallow copy B d; d = b; //shallow assignment } 

Will the shallow copy\assignment call member A a's copy constructor\assignment operator overloading? Or shortly does shallow copy perform member objects' user-made copy constructor & assignment operator or a shallow one as well?

1
  • 3
    There is nothing "shallow" about these copies. Commented Jan 26, 2021 at 16:17

2 Answers 2

4

The term "shallow copy" is used to describe copies where, after a "shallow copy", the two objects internally reference the same object in some way. As such, manipulating one object may conceptually manipulate a value visible through the other.

Unless the value of the int stored in A is a reference to an object somewhere, nothing in A or B references an object. Therefore, implicitly-defined copies of such objects are not "shallow" (or "deep"). That qualification simply doesn't apply to objects that aren't referencing other objects.

The implicitly defined copy constructor/assignment will perform a member-wise copy of each subobject. So long as those subobjects have copy constructors/assignment operators, they will be called by the implicitly defined versions.

Sign up to request clarification or add additional context in comments.

Comments

-2

Then the answer is yes, the copy constructor will be called, but the assignment operator will not.

The copy constructor will be called because the defaulted copy constructor is called, but the assignment operator is not. The defaulted assignment operator will call the defaulted copy constructor, and the defaulted copy constructor will call the copy constructor of the base class, but the defaulted assignment operator is not called.

The reason is simple: the defaulted assignment operator is not called because the defaulted assignment operator is declared "A& operator=(const A& a)".

The above is a case in which the calling convention (the "= default" is a member function calling convention) is used.

2 Comments

The second paragraph of this answer doesn't make any sense to me. "The defaulted assignment operator will call the defaulted copy constructor" an assignment operator doesn't call a copy constructor because there's nothing to construct. Both objects are already constructed before the assignment.
A class's default compiler-generated assignment operator is just a member-by-member assignment from one object to another. As such, it should invoke the assignment operator of each member that is being copied. So, in this case, the generated B::operator= should act like this: class B { public: A a; B(){} B& operator=(const B& b) { a = b.a; return *this; } }; thus invoking A::operator=

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.