Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The * in C++ Initialisations [duplicate]

Tags:

c++

Possible Duplicate:
The Definitive C++ Book Guide and List

What does the * mean when initialising a class? Normally in AS3 I would do this:

MyClass myClass = new MyClass

But I have seen this in c++

 MyClass *myClass = new MyClass

What is the star for? I've seen it used sometimes and not others.

like image 638
panthro Avatar asked Oct 16 '12 13:10

panthro


2 Answers

The asterisk in C++ means many things depending on its place in the program. In this specific instance, it modifies the meaning of myClass to be a pointer to an instance of MyClass, rather than an instance of MyClass.

The difference between the two is that the lifetime of an instance ends when it goes out of scope, while an instance that you allocate and reference through a pointer remains valid even after a pointer goes out of scope.

It is valid to have a declaration like this:

MyClass myClass; // no "new"

In this case, it is not necessary to use new, but the instance's life time is tied to the scope of the variable myClass.

like image 120
Sergey Kalinichenko Avatar answered Oct 24 '22 01:10

Sergey Kalinichenko


It's called a pointer. If you're using a C++11 compatible compiler, you can do the following:

auto myClass = std::make_shared<MyClass>();

If you were using a "raw" pointer, you would need to manually delete it when you are finished with the memory, with the shared_ptr, this isn't necessary.

like image 2
Mark Ingram Avatar answered Oct 24 '22 00:10

Mark Ingram