What is * for in the expression "Foo* foo = new Foo" in C++?

Asked

Viewed 356 times

6

I was looking into this question done in SOEN. There is teaching to instantiate a certain class.

I was able to understand more or less how it works, because when I use my example, it is giving error when compiling.

class Pessoa {

    int idade;
    float tamanho;

};

int main()
{
     Pessoa pessoa = new Pessoa();
}

However the following error appears:

error: Conversion from ːPessoa*' to non-scalar type ːPessoa' requested Person person = new Person ();

Error is fixed when I put an asterisk in front of the word Pessoa.

 Pessoa* pessoa = new Pessoa ();

So, what is the function of the asterisk in this case? What does it indicate?

  • It’s a good question, but it deserved someone’s -1. Happy 2016, srsrsrsrsrsrsrs.

1 answer

8


How the operator was used new, which is a memory allocator in the heap, the only way to reference the allocated object is through a pointer, and the * is the way to declare a variable saying that it is a pointer to a type. The new always returns a pointer. It is equivalent, but more flexible, than the malloc() of the C.

So Pessoa * can be read as "pointer to Person". Which is quite different from just Pessoa. The latter would have a sufficient size in the variable for the entire data structure it makes up Pessoa but for this I could not use the new. In the case of Pessoa * needs only pointer space (4 or 8 bytes on the most common platforms nowadays) in the variable. The data will be placed elsewhere, so it is pointed out.

Always remember that in C++ you have to take care of the details of memory, you do not access it as transparently as in other languages. This gives power, but brings responsibility.

I know it’s just a test, but for such small classes it’s better to allocate without the new. And in this case it’s best to use a struct than a class, even if it makes little real difference, it’s just to make it clear that it’s ideal to allocate in stack.

  • 1

    With Great power comes Great Responsibility.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.