TestClass(const TestClass& obj);
int getSize() const;
TestClass::TestClass() : m_Size(0)
m_Object = new OtherClass();
// This shouldnt work right? Because m_Size is private? But it does work..
// My initial code was m_Size(obj.getSize()) - Also correct
TestClass::TestClass(const TestClass& obj) : m_Size(obj.m_Size)
//Some omitted method implementations here...
I'm obviously not understanding something here, maybe someone can explain it to me :)
My guess would be that I can access the private parts of obj (A TestClass object) directly, because the Copy Constructor uniquely allows this behaviour?
I also found another explanation here after a bit of search:
Because the copy constructor is a member of TestClass, and our parameter is a TestClass, we can directly access the internal private data of our parameter.
And some added info for anyone interested:
The parameter MUST be passed by reference, and not by value.
A copy constructor is called when a parameter is passed by value. If we pass the obj parameter by value, it would need to call the copy constructor to do so. But calling the copy constructor again would mean the parameter is passed by value again, requiring another call to the copy constructor. This would result in an infinite loop.