C++ : Array of Objects of a Class with Overloaded Constructors -


suppose have 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 want create array of objects of "myclass" follows -:

int main() {     myclass arr[]= {5};  // 1 element simplicity... } 

but when , following error -:

in function ‘int main()’:
|47|error: no matching function call ‘myclass::myclass(myclass)’
|47|note: candidates are:
|36|note: myclass::myclass(myclass&)
|36|note: no known conversion argument 1 ‘myclass’ ‘myclass&’
|32|note: myclass::myclass(int)
|32|note: no known conversion argument 1 ‘myclass’ ‘int’

but when remove copy constructor myclass(myclass &a) class , don't errors , works fine...

so questions -:

1). why happening?? isn't myclass(int n=0) better match copy constructor here??

2). how compile , considering want both , copy constructor integer constructor in class??

note: using gcc version 4.7.3 on ubuntu 13.04 ( if of relevance. )

the initialization semantics in case copy initialization. copy initialization formally converts arguement, copies it. converted arguement not lvalue, cannot bind non-const reference in copy constructor. if don't define copy constructor, compiler defines 1 you, takes const reference. you're copy constructor should take const reference well, since doesn't modify argument.

note compiler allowed optimize out copy construction. if program legal if didn't.


Comments