Asaf Brom
Asaf Brom

Reputation: 11

Eclipse fails to resolve a method from a vector made of class pointers (C++)

I have a class that looks like this:

enum DATA_TYPE {bla, bla2};
class Mem_Data
{
private:
    DATA_TYPE m_eType;
    uint32    m_nLineAddr;
    uint32    m_nPhysAddr;
    uint32    m_nSize;
    int       m_nIndex;
public:
    Mem_Data(DATA_TYPE eType, uint32 nLineAddr,uint64 nPhysAddr,uint64 m_nSize, int nIndex = 0);
    DATA_TYPE GetType();
    int GetIndex();
    uint32 GetLineAddr();
    uint32 GetPhysAddr();
};

I then create a vector that is made from pointers of this class:

Vector<Mem_Data *> m_dataVec;
m_dataVec.push_back(new MemData());
m_dataVec.push_back(new MemData());
m_dataVec.push_back(new MemData());

(Of course I put data to match my constructor but this is just an example)

But when I try to access a function from the class inside the vector Eclipse fails to resolve it.

m_dataVec.front()->GetType()

The above fails to resolve. However this seems to work:

Mem_Data *p = m_dataVec.front();
p->GetType();

This does resolve but it seems inelegant as it forces me to add another variable and not access the class instance directly.

Would appreciate any suggestions.

Upvotes: 1

Views: 280

Answers (2)

Asaf Brom
Asaf Brom

Reputation: 11

This is what I ended up using:

((Mem_Data*)cve.m_dataVec[0])->GetLineAddr()

It seems that the vector implementation kept trying to use the consts [] operator instead of the normal [] operator, and this solved it.

Upvotes: 0

Steve Lorimer
Steve Lorimer

Reputation: 28679

vector.begin() returns an iterator.

In order to get access to the data stored in the vector, or more specifically, to the data the iterator points to, you need to dereference the iterator.

you do this with either operator*() or operator->().

In your example, you would do this as follows:

auto iterator = m_dataVec.begin(); // get iterator from vector
Mem_Data *p = *iterator;           // dereference iterator to get Mem_Data pointer

You can dereference begin() in one line using *:

*m_dataVec.begin() // this is a Mem_Data pointer

You can then get access to the data the pointer is pointing as using either * or ->:

(*m_dataVec.begin())->GetType();

Note here the parens around (*m_dataVec.begin()) are necessary because of operator precedence.

Another way to do the same is double-dereference, which would give you access to Mem_Data&:

**m_dataVec.begin().GetType(); // double deref - 1st the iterator, then the pointer

Upvotes: 1

Related Questions