Im having difficulty in understanding copy constructors so the operator overloading.can any one explain me in detail the following program and how copy constructor works.I also dont understand why b.i is used in the constructor initializer list.
For example in operator overloading "+"they use i+b.i" does it mean current val +prev value??
It means "perform some operation on i and b.i". Hopefully that operation has something akin with addition, but it could also say... test for equality, print a novel, etc. In the context of your question, the result of that operation is probably used to initialise a member variable, bit that is unusual for a copy constructor since the copy is usually identical in the values of its members (or the value of what they point to, in the case of pointer members) with the original.
C + C++ Compiler: MinGW port of GCC
Build + Version Control System: SCons + Bazaar
It means "perform some operation on i and b.i". Hopefully that operation has something akin with addition, but it could also say... test for equality, print a novel, etc. In the context of your question, the result of that operation is probably used to initialise a member variable, bit that is unusual for a copy constructor since the copy is usually identical in the values of its members (or the value of what they point to, in the case of pointer members) with the original.
Hi thank you for the reply mate.What i dont understand is that since constructor is always associated with the object so generally we declare only "i" and not "b.i" but when it comes to copy constructor why do we declare b.i.For example in the following code
Code:
class Integer {
int i;
public:
Integer(int ii) : i(ii) {}
const Integer
operator+(const Integer& rv) const {
cout << "operator+" << endl;
return Integer(i + rv.i);
}
Integer&
operator+=(const Integer& rv) {
cout << "operator+=" << endl;
i += rv.i;
return *this;
}
};
int main() {
cout << "built-in types:" << endl;
int i = 1, j = 2, k = 3;
k += i + j;
cout << "user-defined types:" << endl;
Integer ii(1), jj(2), kk(3);
kk += ii + jj;
}
What i dont understand is that since constructor is always associated with the object so generally we declare only "i" and not "b.i" but when it comes to copy constructor why do we declare b.i.
You declare a Parent object named b. Since Parent has an i member, you can then use b.i.
C + C++ Compiler: MinGW port of GCC
Build + Version Control System: SCons + Bazaar
Bookmarks