Search code examples
c++pointersoperatorsdereferenceoperator-precedence

Why can't I dereference a pointer to an object that's an array-element using the indirection operator?


Is it not possible to dereference a pointer to an object that's stored in an array using the indirection(dereference) operator or am I doing something wrong?

#include <iostream>

class A {
    public:
        virtual void test() {
            std::cout << "A\n";
        }
};

class B : public A {
    public:
        void test() {
            std::cout << "B\n";
        }
};


int main() {
    A* v[2];

    v[0] = new A();
    v[1] = new B();

    v[0]->test();
    *(v[1]).test(); // Error! If the arrow operator is used instead
                    // though, the code compiles without a problem.

    return 0;
}

Here is the error I get:

$ g++ -std=c++11 test.cpp && ./a.out 
test.cpp: In function ‘int main()’:
test.cpp:26:13: error: request for member ‘test’ in ‘v[1]’, which is of
pointer type ‘A*’ (maybe you meant to use ‘->’ ?)
    *(v[1]).test();

Solution

  • According to the Operator Precedence, operator.(member access operator) has higher precedence than operator*(indirection/dereference operator) , so *(v[1]).test(); is equivalent to *((v[1]).test());, which is not valid. (You can't call test() on v[1] which is A* via opeartor..)

    Change it to

    (*v[1]).test();