Doubt on the copy constructor

Hi friends :).

I have a doubt on the copy constructor in C++. Something is not clear to me. If we consider the following code,

class sample
{
int a;
public:
sample();
sample(int);
sample(const sample &);
~sample();

void display();
};
sample::sample(const sample &s)
{
a=s.a;
}


in this piece of code, "s.a" refers to the data member of the object s.

Ok...

But then, what does "a=s.a" refer to?
what is this "a" here?
To which object does it belong to...?

I actually posted a part of a program here. If the question is not clear, I will surely send the whole program...Thank you
But then, what does "a=s.a" refer to?
what is this "a" here?
To which object does it belong to...?

The same as it would in any other method of your class - it belongs to this.
Last edited on
MikeyBoy is right.

Giving an example to help you out
1
2
3
4
5
int main(){
sample S1(5) //S1.a is set to 5 now
sample S2(S1) // copy constructor is invoked and S2.a is also set to 5 now.
return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class sample
{
    int a;
public:
    sample();
    sample(int);
    sample(const sample &);
    ~sample();

    void display();
};
sample::sample(const sample &s)
{
    a=s.a;
}
Oh...!

It was very simple then.

I have understood it now.

Thank you brothers (MikeyBoy, funprogrammer, L B)!

Have a good weekend...:)
Topic archived. No new replies allowed.