What does it mean to create an object with that asterisk?

Asked

Viewed 4,418 times

7

Although I knew programming for a reasonable time, learning C++ with QT, I came across something I hadn’t seen in other languages. I noticed that some objects (not all) need to be created with an asterisk preceding the name. For example:

QMessageBox *box = new QMessageBox();

That is, the class QMessageBox To be instantiated, you need that asterisk there to the name of the object. My question is: what is the meaning of that asterisk? Has something to do with arrays, or pointers?

I thank anyone who gives me some clue so I can at least start searching on Google for the subject. I should search for what?

2 answers

4


When there is an asterisk next to the variable name it means it is a pointer. But, it is also possible to declare pointers keeping the asterisk next to the variable type. The two forms below have the same meaning.

int *pnumber1;
int* pnumber2;

Well, but what is a pointer?

A pointer is a variable that stores an address in memory that contains data of a certain type.So the two lines above represent "an integer pointer".

inserir a descrição da imagem aqui


Why use pointers?

  • we can use pointer "notation" to manipulate arrays, which is often "faster";
  • pointers facilitate access to large portions of data;
  • pointers allow dynamic memory allocation;


An example using pointers

#include <iostream>

int main()
{
    int number = 10;
    int* pnumber;

    pnumber = &number;

    std::cout << "Value-Of number variable  : " << number << std::endl
              << "Address-Of number variable: " << pnumber << std::endl
              << "Value-Of pnumber variable : " << pnumber << std::endl
              << "Value-Of pnumber pointer  : " << *pnumber << std::endl;


    return 0;
}

The exits will be:

Value-Of number variable : 10
Address-Of number variable: 003BFCCC
Value-Of pnumber variable : 003BFCCC
Value-Of pnumber Pointer : 10

Source: Blog do Elemar Jr.

2

This instruction declares the variable box pointer.

Pointers, unlike common variables, contain no data but an address for some data.

This is a very complex and confusing subject at first. Take a look here: Pointers in C.

  • Interesting!!! I will try to give a thorough in the subject to understand better. Thanks to all who answered!

Browser other questions tagged

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