I\'m trying to understand something in C++. Basically I have this:
class SomeClass {
public:
SomeClass();
private:
int x;
};
SomeClass::
What you are doing in the first line of main() is to allocate a SomeClass object on the stack. The new
operator instead allocates objects on the heap, returning a pointer to the class instance. This eventually leads to the two different access techniques via the .
(with the instance) or with the ->
(with the pointer)
Since you know C, you perform stack allocation every time you say, for example int i;
. On the other hand, heap allocation is performed in C with malloc(). malloc() returns a pointer to a newly allocated space, which is then cast to a pointer-to something. example:
int *i;
i = (int *)malloc(sizeof(int));
*i=5;
While deallocation of allocated stuff on the stack is done automatically, deallocation of stuff allocated on the heap must be done by the programmer.
The source of your confusion comes from the fact that C# (which I don't use, but I know it is similar to Java) does not have stack allocation. What you do when you say SomeClass sc
, is to declare a SomeClass
reference which is currently uninitialized until you say new
, which is the moment when the object springs into existence. Before the new
, you have no object. In C++ this is not the case. There's no concept of references in C++ that is similar to C# (or java), although you have references in C++ only during function calls (it's a pass-by-reference paradigm, in practice. By default C++ passes by value, meaning that you copy objects at function call). However, this is not the whole story. Check the comments for more accurate details.