Usama Fayyaz
Usama Fayyaz

Reputation: 51

Difference between these two declarations of dynamic arrays of objects of type test?

Why does the pointer ptr allows us to access its member function through the dot operator . while pt doesn't as it requires the indirection operator ->?

int n = 5;
test* ptr = new test[n];
ptr[1].print();
test* pt[45];
pt[1] = new test(2,3);
pt[1]->print();

Upvotes: 0

Views: 40

Answers (2)

songyuanyao
songyuanyao

Reputation: 172924

Because they're different things.

ptr is a pointer of type test*, it points to the 1st element of the array test[n], whose elements are of type test, then ptr[1] gives the 2nd element with type test.

pt is an array, whose elements are of type test*, then pt[1] gives the 2nd element with type test*.

Upvotes: 1

Oblivion
Oblivion

Reputation: 7374

because ptr is an array and ptr[1] alreadey derefrenced the pointer. While pt is array of pointers you need to derefrence twice.

Upvotes: 0

Related Questions