constructors

class A
{
public:
A(A &);
{...}
}

int main
{
A obj1;
A obj2(obj1); and A obj1=obj2; (what is difference between these statements)
}
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
no ..both r valid..

in 1st..argument passed is object
but i dont knw about 2nd
it's different, depending on how you define your constructor...
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
If you are discussing copy constructor , both seem same to me.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class A {
    private :
    int a ;

    public:
        A() {
          a = 0;
         } 

        A(A &object) { 
           a = object.a ; // not sure if this is correct
        }
};

int main()
{
     A obj1;
     A obj2 = obj1; // this one
     A obj3(obj1);  // this one
}


closed account (zb0S216C)
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
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
Topic archived. No new replies allowed.