0

I found this code on the internet. I am a bit confused about the calling of the copy constructor and I just wanted to know why the copy constructor is called when the display function is called?

#include<iostream>
using namespace std;

class myclass
{
int val;
int copynumber;
public:
    //normal constructor
    myclass(int i)
    {
        val = i;
        copynumber = 0;
        cout<<"inside normal constructor"<<endl;
    }
    //copy constructor
    myclass (const myclass &o)
    {
        val = o.val;
        copynumber = o.copynumber + 1;
        cout<<"Inside copy constructor"<<endl;
    }
    ~myclass()
    {
        if(copynumber == 0)
        cout<<"Destructing original"<<endl;
        else 
        cout<<"Destructing copy number"<<endl;
    }
    int getval()
    {
        return val;
    }
};

void display (myclass ob)
    {
        cout<<ob.getval()<<endl;
    }

int main()
{
myclass a(10);
display (a);
return 0;
}

2 Answers2

3

In the display method you are passing the parameter by value, so obviously there will be a copy made and sent to the function. Learn the difference of pass by value and reference. this and this tutorials may be useful.

Community
  • 1
  • 1
Rakib
  • 7,435
  • 7
  • 29
  • 45
0

It is being invoked because you are passing the object value rather than by const reference. If you passed a const myclass& ob, instead, then the copy constructor wouldn't get called. However, as is, your function is set up to create a copy of the parameter (that is, your function operates on a copy, not the original object).

Michael Aaron Safyan
  • 93,612
  • 16
  • 138
  • 200