I have some questions about C++ from a C# developer.
For a few days I have been looking at some C++ code, and I have the following questions:
- When do use
Foo::,Foo.andFoo->? - When do I use a real constructor and when just
String a;(sometimes I need to do something likeString a("foo");) - What is the difference between these signatures:
int foo(int a)andint foo(int &a)?
::is used either to explicitly specify a namespace (std::string, for example, for the string class in the namespacestd), or for static members of a class..is used much as in C#, to refer to a member of a class.->is used with pointers. Ifpis a pointer to an objectobj, thenp->xhas the same meaning asobj.x.When you need to.
String ais roughly equivalent to C#’sa = new String()(with the caveat that ifStringis a non-POD type, it may contain uninitialized members.)If you need
ainitialized to a specific value, you do that. (either withString a("foo"), or withString a = "foo")The
&denotes a reference. It’s not quite a C# reference, but there are similarities. In C#, you have value types and reference types, and reference types are always passed by reference.In C++, there’s no such distinction. Every type can be passed by value or by reference. The type
T&is a reference to T. In other words, given the following code:foowill get a reference toi, which means it it can modify the value ofi.barwill get a copy ofi, which means that any modifications it makes will not be reflected ini.You often use
const T&(a reference toconst T) as a way to avoid the copy, while still preventing the callee from modifying the object.