문제

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