"clTest2.MYTEST(clTest);" actually triggered "CTest(const CTest &)" to
create an internal object. After ""clTest2.MYTEST(clTest);" is
"executed,clTest.i" is "2", not "3".
Can I say C++ objects are value type?
Thank you!
class CTest
{
public:
int i;
CTest(const CTest &)
{
i = 1;
};
CTest(void)
{
i = 2;
}
void MYTEST (CTest clTest)
{
clTest.i = 3;
}
};
int main ()
{
CTest clTest;
CTest clTest2 = clTest;
clTest2.MYTEST(clTest); //Test C++ object
}
If you must use the C# terminology: Yes, C++ classes are closer to "C#
value types" than "C# reference types" with respect to the implicit
indirection you have with C# class types.
Cheers,
SG
Yes, unless you code otherwise. You can pass by reference or by pointer,
but default is by value. That is how structs are passed in C, and C++
classes are just extended C structs.
--
Q: Why did the chicken cross the road?
A: He was giving it last rites.
Well your test is not suitable to answer your question. The method
MYTEST takes an object as parameter (the way you describe it).
clTest.i = 2; //assigns a value to the object
clTest2.MYTEST(clTest); //this creates an object on the stack copying
the content from clTest.
-> call of MYTEST
clTest.i = 3; //assigns 3 to the local object
<- removes the object from stack
clTest.i is not changed.
This behavior is typical for method calls with parameter declared as
objects, but it has nothing to do with value or reference types. It's
the way you've declared the method.
To analyse or even to design value or reference types in C++ you must
design the class in the correct way first.
For instance following can not be realy used as value type:
class CTest
{
public:
CTest(){}
void release() { delete this; }
void MYTEST(CTest Test) { ... }
protected:
virtual ~CTest(){}
};
The compiler will not allow you to compile a statement like this
{
CTest clTest;
CTest clTest2;
clTest2.MYTEST(clTest); //<< compile error: can't call
CTest::~CTest() for local parameter object
} //<< compile error: can't call CTest::~CTest() for clTest and
clTest2
Objects of class CTest can not be put on the stack and must be created
with new() on the heap. This can help if a class should work only as a
reference type. But a reference type within C# has more features such
as for instance memory management using garbage collection.
Other topics related to C++ and C#:
http://www.xatlantis.ch/education/interfaces.html
http://www.xatlantis.ch/education/csharp_binding.html