Sep 9, 2012 at 7:43am Sep 9, 2012 at 7:43am UTC
class A
{
public:
A(A &);
{...}
}
int main
{
A obj1;
A obj2(obj1); and A obj1=obj2; (what is difference between these statements)
}
Sep 9, 2012 at 7:53am Sep 9, 2012 at 7:53am UTC
1 2 3 4 5 6 7 8 9 10 11 12
class A {
public :
A() { }
A(A &) { }
};
int main()
{
A obj1;
A obj2 = obj1; // this one
A obj3(obj1); // this one
}
A obj3(obj1)
: This code does absolutely nothing other than pass the object into the constructor.
A obj2 = obj1
:
http://codepad.org/O3lJsQjo
In this case, they are both completely different.
Last edited on Sep 9, 2012 at 8:09am Sep 9, 2012 at 8:09am UTC
Sep 9, 2012 at 7:56am Sep 9, 2012 at 7:56am UTC
no ..both r valid..
in 1st..argument passed is object
but i dont knw about 2nd
Sep 9, 2012 at 8:03am Sep 9, 2012 at 8:03am UTC
it's different, depending on how you define your constructor...
Sep 9, 2012 at 8:09am Sep 9, 2012 at 8:09am UTC
no ..both r valid..
in 1st..argument passed is object
but i dont knw about 2nd
The code you provided does not compile.
Last edited on Sep 9, 2012 at 8:09am Sep 9, 2012 at 8:09am UTC
Sep 9, 2012 at 10:08am Sep 9, 2012 at 10:08am UTC
vgoel38 wrote:1 2
A obj1;
A obj2(obj1); and A obj1=obj2; (what is difference between these statements)
There's no difference between the two. During a declaration statement, the assignment operator will invoke the respective constructor based on the operand on the right-hand side of the assignment operator. For instance:
1 2 3 4 5 6 7 8 9 10
struct Sample
{
explicit Sample(int ) { }
};
int main()
{
Sample sample_a = Sample(10); // Invokes "Sample::Sample(int)"
Sample sample_b = sample_a; // Invokes "Sample::Sample(Sample &)"
}
Wazzak
Last edited on Sep 9, 2012 at 10:18am Sep 9, 2012 at 10:18am UTC
Sep 9, 2012 at 10:12am Sep 9, 2012 at 10:12am UTC
I think
Sample sample_a = 10;
is equivalent to
Sample sample_a(Sample(10));
. If there are no appropriate copy/move constructor it will fail.
1 2 3 4 5 6 7 8 9 10
struct Sample
{
Sample(int ) { }
Sample(Sample const &) = delete ;
};
int main()
{
Sample sample_a = 10; // error: use of deleted function ‘Sample::Sample(const Sample&)’
}
Last edited on Sep 9, 2012 at 10:45am Sep 9, 2012 at 10:45am UTC