0

In this program, I am supposed to call animal.at(0)->makeSound() in main() and have it return "Woof" from the public member function makeSound() for Dog. However, when I compile the code as written, it gives me an error:

base operand of '->' has non-pointer type

While I know there are other ways around this, I am not allowed to modify any of this code except for the vector type and the element list of the vector, as this is a practice problem from an old homework I got wrong.

If somebody could tell me how to set up the array properly (vector <MISSING_TYPE> animal {MISSING VECTOR ELEMENT};) so that it will compile, you will be saving me for finals. What I have now is currently incorrect.

#include <iostream>
#include <vector>
using namespace std;

class Animal
{
public:
  virtual void makeSound() {  
    cout << "Animal!" << endl;
  }
};

class Dog : public Animal
{
public:
  void makeSound() {
    cout << "Woof" << endl;
  }
};
 
  
int main()
{
  Dog dog;
    
  vector<Animal> animal {dog};
  animal.at(0)->makeSound();
  
  return 0;
}
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • 2
    animal.at(0) is of type Animal, not Animal*. So you just use a `.` not an `->` – xaxxon May 02 '22 at 00:09
  • `->` is the dereference access oprator. Since `animal` contains objects, not pointers to objects `->` is ill formed. Use `.` instead – Lala5th May 02 '22 at 00:09
  • `vector` is not a vector of pointers. `animal.at(0).makeSound();` is a correct call. I am pretty sure if you read the error message carefully, the compiler suggests you using the period. – 273K May 02 '22 at 00:10

2 Answers2

3

The compiler error is because the vector is holding Animal objects, not Animal* pointers to objects, so you would have to use the . operator instead of the -> operator to access the makeSound() member, eg:

animal.at(0).makeSound();

// or, since you KNOW there is 1 object in the vector, the
// bounds checking of at() is redundant, use operator[] instead:
//
// animal[0].makeSound();

Online Demo

However, although that will fix the compiler error, calling makeSound() at runtime will print "Animal!" instead of "Woof", because you are not actually storing a Dog object in the vector, you are storing an Animal object due to object slicing. To fix that, you would need to instead store an Animal* pointer to the Dog object, eg:

int main()
{
  Dog dog;
    
  vector<Animal*> animal {&dog};
  animal.at(0)->makeSound();
  // or: animal[0]->makeSound();
  
  return 0;
}

Online Demo

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
0

animal.at(0) is of type Animal, not Animal*. So you just use a . not an ->

If you made animal a vector<Animal*> then you'd use ->

xaxxon
  • 19,189
  • 5
  • 50
  • 80