class P {
public:
P() {}
~P() {}
P(P const & p) { //<--- Question 1
setX(p.getX()); //<--- Question 2
setX(p.x); //<--- Question 3
x = p.x; //<--- Question 3
}
void setX(int i) {
x = i;
}
int getX() {
return x;
}
private:
int x;
};
Question 1 Whats the difference between P(P const & p) and P(const P & p) ? Question 2 Why this does not work ? Question 3 Why does this work, (accessing the private data memeber directly) ?
Q1. There is no difference between these two declarations.
Q2. It does not work because you are trying to call non-const member function for const object (because you declared the parameter as a const reference). If you will rewrite function getX as
1 2 3 4
int getX() const
{
return x;
}
it will work.
Q3. It works because the objedts are of the same type.
Answer 1 There is no difference Answer 2 Because getX is not const so you can only call it on non-const objects. If you define getX as this it will work
1 2 3
int getX() const {
return x;
}
Answer 3 Because all member functions of P has access to the private member's of P.