Jaspreet said:
#include <iostream>
using namespace std;
class stud
{
public:
stud (stud &s)
{
cout<<endl<<"copy";
}
stud(int a)
{
cout<<endl<<"1-arg constructore";
}
};
int main()
{
stud s=stud (5);
return (EXIT_SUCCESS);
}
[snip]
Not sure how, the call "stud s=stud(5);" would call a copy constructor.
It should not. Let me know if I am wrong..
You are wrong
The sequence of events in
stud s = stud(5);
is:
create a temporary stud object and initialize it with 5 using
the stud::stud(5) constructor.
create the object s and initialize it with the previously generated
temporary object. For this the copy constructor is used (since this
is object creation. An assignment is never used for object initialization,
even if you write '=')
Your program failes because a temporary cannot be bound to a reference which
is not const. Now look at your 'copy constructor':
stud (stud &s)
{
cout<<endl<<"copy";
}
It takes the argument by reference. But this reference is not const. Thus the
temporary cannot be bound to it and hence the compilation fails.
stud s = stud(5);
is equivalent to
stud s ( stud(5) );
Don't confuse yourself. Even if you write '=', this is *not* an assignment.
This is the construction of a new object and for that *always* a constructor
is used. (Assignment would require that the object existed previously, but this
is an object under construction, thus assigment cannot be used)