C
CPP beginner
Hi , could you explain me the mechanism of copy constructor:
#include <iostream>
#include <algorithm>
class FOO
{
public:
int size;
int* data;
explicit FOO(int size):size(size), data(new int[size]) {}
~FOO(){delete[] data;}
FOO(FOO & copy): size(copy.size), data(new int[copy.size])
{std::copy(copy.data, copy.data + copy.size, data);}
};
FOO f(FOO A)
{return A;}
int main()
{
FOO first(2);
FOO copy = f(first);
}
This code return:
test.cpp: In function ‘int main()’:
test.cpp:25: error: no matching function for call to ‘FOO::FOO(FOO)’
test.cpp:13: note: candidates are: FOO::FOO(FOO&)
But When i replace FOO(FOO & copy) by FOO(const FOO & copy), it works.
f(first) returns a FOO object, it is temporay so is it non const ?
I would like to understand the mecanism.
Thank you very much.
#include <iostream>
#include <algorithm>
class FOO
{
public:
int size;
int* data;
explicit FOO(int size):size(size), data(new int[size]) {}
~FOO(){delete[] data;}
FOO(FOO & copy): size(copy.size), data(new int[copy.size])
{std::copy(copy.data, copy.data + copy.size, data);}
};
FOO f(FOO A)
{return A;}
int main()
{
FOO first(2);
FOO copy = f(first);
}
This code return:
test.cpp: In function ‘int main()’:
test.cpp:25: error: no matching function for call to ‘FOO::FOO(FOO)’
test.cpp:13: note: candidates are: FOO::FOO(FOO&)
But When i replace FOO(FOO & copy) by FOO(const FOO & copy), it works.
f(first) returns a FOO object, it is temporay so is it non const ?
I would like to understand the mecanism.
Thank you very much.