nehem
nehem

Reputation: 13662

Not able to call a public method on pointer stored in a container

Strangely I am getting compilation error in C++ for the following code.

class A
    {
    public:
        void sayHai()
        {
            cout << "\n Hai";
        }
    };

    int main(int argc, char** argv)
    {            
        vector< A* > vectorA;
        vectorA.push_back(new A());
        for (vector< A* >::iterator iter = vectorA.begin(); 
             iter != vectorA.end(); 
             ++iter)
            *iter->sayHai();
    }

Here I am storing pointer to class A in a vector. And when I try to call a public method I am getting the following compilation error.

VectorExample.cpp: In function 'int main(int, char**)':
VectorExample.cpp:30: error: request for member 'sayHai' in 
    '* iter.__gnu_cxx::__normal_iterator<_Iterator, _Container>::operator-> 
    [with _Iterator = A**, _Container = std::vector<A*, 
    std::allocator<A*> >]()', which is of non-class type 'A*'

Has anyone encountered such situation? Why this is treated as a compilation error? And what should be the necessary approach to resolve this problem?

I compiled the above using g++ (GCC) 4.1.2 20080704 (Red Hat 4.1.2-46)

Upvotes: 1

Views: 116

Answers (2)

Agentlien
Agentlien

Reputation: 5126

This error is due to the operator * having lower precedence than the operator ->.

The line *iter->sayHai();

will be treated as *(iter->sayHai()); In other words, what you have written is equivalent to *( (*iter).sayHi() ) // iter->sayHi equivalent to (*iter).sayHi() This fails to compile because there is no member called sayHi in the type of iter.

Instead, replace the line in question with: (*iter)->sayHai(); This will first dereference iter and then call sayHi as expected on the object referenced by the resulting pointer.

Upvotes: 1

Sodved
Sodved

Reputation: 8598

Probably just be operator precedence. The error message looks like its trying to call the sayHai method of the iterator. So do this instead:

(*iter)->sayHai();

Upvotes: 7

Related Questions