Suppose i have a class "myclass" -:
class myclass
{
public:
int n;
myclass(int n=0)
{
this->n=n;
}
myclass(myclass &a)
{
this->n=a.n;
}
~myclass()
{
cout<<n<<"\n";
}
};
Now i want to create an array of objects of "myclass" as follows -:
int main()
{
myclass arr[]= {5}; // Only 1 element for simplicity...
}
But when i do this , i get the following error -:
In function ‘int main()’:
|47|error: no matching function for call to ‘myclass::myclass(myclass)’
|47|note: candidates are:
|36|note: myclass::myclass(myclass&)
|36|note: no known conversion for argument 1 from ‘myclass’ to ‘myclass&’
|32|note: myclass::myclass(int)
|32|note: no known conversion for argument 1 from ‘myclass’ to ‘int’
But when i remove the copy constructor myclass(myclass &a) from the class , i don't get any errors and everything works fine...
So now my questions are -:
1). Why is this happening?? Isn't myclass(int n=0) a better match than the copy constructor here??
2). How to successfully compile it , considering I want both , the copy constructor as well as the integer constructor in my class??
NOTE: I am using GCC version 4.7.3 on Ubuntu 13.04 ( If it is of any relevance. )
const myclass& a?std::auto_ptr) where the copy constructor does take a non-const reference. But generally: you want to be able to copy temporaries (which requires a const ref), and you don't modify the object being copied (so you can use a const ref).