somemaker
somemaker

Reputation: 63

How to know a copy constructor is called?

Considering the example, I know that assigning one object to other, calls copy constructors, does Line 2 also call a copy constructor here. What are the total number of copy constructor calls made here?

class Sample{ 
  public:
     void compare(Sample args){    }
};
int main(){
  Sample  s1;
  Sample  s2=s1; //Line 1
  s1.compare(s2); // Line 2
}

Upvotes: 3

Views: 415

Answers (1)

Vlad from Moscow
Vlad from Moscow

Reputation: 311068

Just add the copy constructor to your class definition and see the result.

#include <iostream>
class Sample{ 
  public:
    Sample() = default;
    Sample( const Sample & ) { std::cout << "Sample( const Sample & )\n"; }
     void compare(Sample args){    }
};

int main(){
  Sample  s1;
  Sample  s2=s1; //Line 1
  s1.compare(s2); // Line 2
}

The program output is

Sample( const Sample & )
Sample( const Sample & )

If to comment the call

  // s1.compare(s2); // Line 2

then the output will be

Sample( const Sample & )

Upvotes: 4

Related Questions