I know that the arrow operator ->
is used to dereference objects, but I'm quite confused with its usage on this piece of code from Visual Studio .net framework:
private: System::Void button3_Click(System::Object^ sender, System::EventArgs^ e) {
if (txtDisplay->Text->Contains("-")){ //this could be phrased like (*txtDisplay).Text, why does the 'Text', a data member could contain a method named 'Contains()', and if 'Text' is not a data member but rather a class object, why can we assign a value into just like the line next after.
txtDisplay->Text = txtDisplay->Text->Remove(0, 1); //in here we have assign a value of 'Text' and because of that i assumed 'Text' was a data member
}
else {
txtDisplay->Text = "-" + txtDisplay->Text;
}
}
And another question, what's the main purpose of allocating objects in the heap, as I assume the object txtDisplay
is in the heap since it's a pointer?
You're confusing C++ with the .NET framework and its C++ extensions.
The txtDisplay
object has a Text
property which is likely a System::String^
which means it's a managed object. So you can 'assign' values to a managed object much like you can assign values to any other assignable type or that have the assignment operator overloaded.
For example, in .NET C++ you can do something like the following:
System::String^ SomeFunction(int i) {
return i.ToString();
}
Obviously, the int
type is a basic type that does not have any member methods; however, since you're using .NET, essentially you're utilizing a pseudo-C++ compiler that actually complies the C++ code into .NET which is then executed via the .NET runtime, which runs bytecode and not pure assembly (which is what traditional C++ is compiled to).
So that's why you can assign to the Text
member.
Regarding whether the objects are allocated in the heap or the stack, that's really up to the .NET compiler/interpreter, but according to what I've read in documentation, there's a good chance it will be in the heap and not the stack, due to its reference counting and garbage collection. I should note that this is purely for the .NET framework and not regarding what would happen if you used ISO/ANSI C++.
It's best to think of .NET C++ like C# with C++-like syntax, and not like ISO C++ as they are really different things; yes you can use ISO C++ in .NET C++, but doing so can result in odd and unexpected behavior due to how the .NET CLR works versus a 'normal' C++ application running in a specific environment.