What does it mean to create an object with an asterisk? [duplicate]

7

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

QMessageBox *box = new QMessageBox();

That is, the class QMessageBox to be instantiated, needs that asterisk there in the name of the object. My question is: what is the meaning of this asterisk? Does it have anything to do with arrays, or pointers?

Thanks to anyone who gives me a clue so I can at least start searching on Google for the subject. Should I search for what?

    
asked by anonymous 19.06.2015 / 01:07

2 answers

4

When you have an asterisk next to the variable name it means that it is a pointer. But you can also declare pointers by 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 "a pointer to integer."

Whyusepointers?

  • Wecanusepointer"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 outputs will be:

Value-Of Number variable: 10
Address-Of number variable: 003BFCCC
Value-Of variable pnumber: 003BFCCC
Value-Of pnumber pointer: 10

Source: Elemar Jr.'s blog

    
19.06.2015 / 14:34
2

This statement declares the variable box as a pointer.

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

This is a very complex subject and it confuses a lot in the beginning. Take a look here: Pointers in C .

    
19.06.2015 / 14:13