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;
}
有帮助吗?

解决方案

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.

其他提示

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).

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top