Home > Back-end >  I am getting a "base operand of ‘->’ has non-pointer type" when calling my function
I am getting a "base operand of ‘->’ has non-pointer type" when calling my function

Time:05-02

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;
}

CodePudding user response:

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

CodePudding user response:

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 ->

  •  Tags:  
  • c
  • Related