dereferencing pointer

Hey y'all, hope I write this question correctly. My question is directed at the line quiz[i]->display();
From what I understand, the -> operator de references the pointer and then calls the member function of that object. My question is why cant I write something like *(quiz[i]).display() ? To me it seems like those two statements are equivalent, where they both say "de reference the pointer and call the member function on what the pointer contains" however the second one doesn't work and I get an error saying "expression must have a class type". Thanks in advance, just trying to make sure I really understand what is going on here.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
    string response;
    cout << boolalpha;

    Question* quiz[3];

    quiz[0] = new Question;
    quiz[0]->set_text("Who was the inventor of C++?");
    quiz[0]->set_answer("Bjarne Stroustrup");

    ChoiceQuestion* cq_ptr = new ChoiceQuestion;
    cq_ptr->set_text("In which country was the inventor of C++ born?");
    cq_ptr->add_choice("Australlia", false);
    cq_ptr->add_choice("Denmark", true);
    cq_ptr->add_choice("Korea", false);
    cq_ptr->add_choice("United States", false);
    quiz[1] = cq_ptr;

    NumericQuestion* nq_ptr = new NumericQuestion;
    nq_ptr->set_text("How many liters are in a gallon?");
    nq_ptr->set_answer(3.78541);
    quiz[2] = nq_ptr;

    for(int i = 0; i < 3; i++)
    {   
        quiz[i]->display();
        cout << "Your answer: ";
        getline(cin, response);
        cout << quiz[i]->check_answer(response) << endl;
    }

}
Last edited on
noblemin wrote:
*(quiz[i]).display()

You have operators there:
1. The dereference *
2. The member access .

In which order are they evaluated?
See table at end of http://www.cplusplus.com/doc/tutorial/operators/

The member access has higher precendence, as if you had written: *((quiz[i]).display())
Pointer has no members. Hence the error.

You have to dereference before you access member:
(*(quiz[i])).display()
and that makes the -> bit simpler syntax:
(quiz[i])->display()
Last edited on
Ah that actually makes perfect sense, thanks for the input.
Topic archived. No new replies allowed.