Copy Constructor

I have some code like the following which is causing me some confusion:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include "OtherClass.h"

class TestClass
{
	public:
	
		TestClass();
		TestClass(const TestClass& obj);
		~TestClass()
		
		int getSize() const;
	
	private:
	
		OtherClass *m_Object;
		int m_Size;

};


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?
Last edited on
You can access private members of the class from its member functions. It doesn't matter what object is is.
Thanks Peter.

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.
Last edited on
Topic archived. No new replies allowed.