What is the use of * in the expression "Foo * foo = new Foo" in C ++? [duplicate]

6

I was analyzing this question made in SOEN. There you are teaching to instantiate a particular 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 'Person *' to non-scalar type 'Person' requested         Person person = new Person ();

The error is resolved when I place 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?

    
asked by Wallace Maxters 05.01.2016 в 15:50

1 answer

8

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

Then Pessoa * can be read as "pointer to Person". That is quite different from just Pessoa . The latter would have a sufficient size in the variable for the entire data structure that compose Pessoa but for this it could not use new . In the case of Pessoa * you need only pointer space (4 or 8 bytes on the most common platforms nowadays) in the variable. The data will be placed elsewhere.

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 it does carry responsibilities.

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

    
05.01.2016 / 15:59