Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get The Object Pointer Is Pointing To

Tags:

c++

I have a QList which I have inserted pointers of objects into. I am trying to iterate through this QList to read the name of these objects. Whenever I do so, I am getting the address of these objects as oppose to reading the object name itself. I am wondering how would I be able to read the object name instead of the address?

QList<MyObject*> newObjectList;
QList<MyObject*>::iterator i;

MyObject *pNewObject = new MyObject(name);
MyObject.append(pNewObject); 

for (i = newObjectList.begin(); i != newObjectList.end(); i++) {
    cout << "\n" << *i << "\n";
}
like image 778
Jon Avatar asked Feb 17 '12 18:02

Jon


People also ask

How do you get the address a pointer points to?

Pointers are said to "point to" the variable whose address they store. An interesting property of pointers is that they can be used to access the variable they point to directly. This is done by preceding the pointer name with the dereference operator (*). The operator itself can be read as "value pointed to by".

Can a pointer point to an object?

In C++, a pointer holds the address of an object stored in memory. The pointer then simply “points” to the object. The type of the object must correspond with the type of the pointer.

How do you get the value a pointer is pointing to in C++?

To get the value pointed to by a pointer, you need to use the dereferencing operator * (e.g., if pNumber is a int pointer, *pNumber returns the value pointed to by pNumber . It is called dereferencing or indirection).

What is a pointer to an object?

A pointer is a type of variable that carries location information. In this case, the example variable will store the address of an Order object that we want to interact with. We initialize the pointer variable by using the C++ new operator to construct a new object of type Order.


2 Answers

When you're dereferencing i, you need to call the function to get the name from your object. Something like this:

for (i = newObjectList.begin(); i != newObjectList.end(); i++) {
    // i right now is the iterator, and points to a pointer. So this will need to be
    // dereferenced twice.
    cout << "\n" << (*i)->getName() << "\n";
}
like image 193
Tyler Gill Avatar answered Sep 28 '22 19:09

Tyler Gill


When you derenference the iterator i (i.e. *i) you a a reference to an object of type MyObject* which is a pointer, you have to dereference that again to get a reference to your object:

*(*i)
like image 35
zdan Avatar answered Sep 28 '22 18:09

zdan