0

A practice question on C++ primer:

class HasPtr
{
public:
    HasPtr(const HasPtr& h) :ps(new string(*h.ps)), i(h.i) { cout << "Copy Constructor" << endl; }
    HasPtr& operator=(const HasPtr& hp) {
        ps = new string(*hp.ps); 
        i = hp.i; 
        cout << "Copy Assignment Constructor" << endl;
    }
    HasPtr(const string& s = string()) :ps(new string(s)), i(0) {};
private:
    string* ps;
    int i;
};

int main()
{
    HasPtr p1;
    HasPtr p2 = p1;
    return 0;
}

Why is the copy constructor called instead of the copy assignment operator at p2=p1? When will the copy assignment operator be called?

gaofeng
  • 393
  • 1
  • 3
  • 11
  • 4
    Because `HasPtr p2 = p1;` is *initialization* and not assignment. Assignment would be something like `HarPtr p1; HasPtr p2; p2 = p1;` – Some programmer dude Mar 31 '23 at 08:18
  • 2
    @Someprogrammerdude Why not turn this into an answer? – arne Mar 31 '23 at 08:19
  • 2
    BTW there is no such thing as a copy assignment constructor. What you have there is the copy assignment operator. It's not a constructor because it doesn't construct anything. Maybe this misunderstanding is the source of your confusion? – john Mar 31 '23 at 08:27
  • To clarify: there is no "copy assignment constructor". You are referring to the "copy assignment *operator*", this is *not a constructor!* This might explain your confusion. – Konrad Rudolph Mar 31 '23 at 08:32
  • C++ Primer does not say "copy assignment constructor" anywhere. It says "copy assignment operator". – molbdnilo Mar 31 '23 at 08:32
  • To avoid the confusion, you have the alternative formats `HasPtr p2(p1);` and `HasPtr p2 {p1};` which doesn't include the `=` token. – BoP Mar 31 '23 at 10:02

0 Answers0