Article 5C16N error: invalid use of non-static member function

error: invalid use of non-static member function

by
maschelsea
from LinuxQuestions.org on (#5C16N)
This is somewhat awkward. In the very next listing, I get the error listed in the title box. Here's my code:
Code:michael@caitlyn 14 $ cat listing14.10.cpp
//Listing 14.10 - Pointers to member functions using virtual methods
//2020-12-23
#include <iostream>

class Mammal
{
public:
Mammal():itsAge(1){}
virtual ~Mammal() {}
virtual void Speak() const = 0;
virtual void Move() const = 0;
protected:
int itsAge;
};

class Dog : public Mammal
{
public:
void Speak() const {std::cout << "Woof!\n"; }
void Move() const { std::cout << "Walking to heel...\n"; }
};

class Cat : public Mammal
{
public:
void Speak() const { std::cout << "Meow!\n"; }
void Move() const { std::cout << "slinking...\n"; }
};

class Horse : public Mammal
{
public:
void Speak() const { std::cout << "Whinny!\n"; }
void Move() const { std::cout << "Galloping...\n"; }
};

int main()
{
void (Mammal::*pFunc)() const = 0;
Mammal* ptr = NULL;
int Animal;
int Method;
bool fQuit = false;

while (fQuit == false)
{
std::cout << "(0)Quit, (1)Dog, (2)Cat, (3)Horse: ";
std::cin >> Animal;
switch (Animal)
{
case 1: ptr = new Dog; break;
case 2: ptr = new Cat; break;
case 3: ptr = new Horse; break;
default: fQuit = true;
}
if (fQuit) break;
std::cout << "(1)Speak, (2)Move: ";
std::cin >> Method;
switch (Method)
{
case 1: pFunc = Mammal::Speak; break;
default: pFunc = Mammal::Move; break;
}
(ptr->*pFunc)();
delete ptr;
}
return 0;
}And here's the error log.
Code:michael@caitlyn 14 $ g++ listing14.10.cpp -o listing14.10
listing14.10.cpp: In function 'int main()':
listing14.10.cpp:61:28: error: invalid use of non-static member function 'virtual void Mammal::Speak() const'
case 1: pFunc = Mammal::Speak; break;
^
listing14.10.cpp:62:29: error: invalid use of non-static member function 'virtual void Mammal::Move() const'
default: pFunc = Mammal::Move; break;
^I don't think I'm trying to use non-static member functions. I mean, I'm not trying to use static member functions. Why would it think that I am? I've typed it in exactly as it appears in the book. No typedefs today. I feel like I've done a million programs exactly like this over the course of the last 14 chapters. I have never encountered this error before. I tried inserting () after Speak and Move and recompiled it and ended up with different errors. Why is this situation so different from all the others? What am I not seeing?latest?d=yIl2AUoC8zA latest?i=XYcKrdXEX2g:82pfaC-7IKc:F7zBnMy latest?i=XYcKrdXEX2g:82pfaC-7IKc:V_sGLiP latest?d=qj6IDK7rITs latest?i=XYcKrdXEX2g:82pfaC-7IKc:gIN9vFwXYcKrdXEX2g
External Content
Source RSS or Atom Feed
Feed Location https://feeds.feedburner.com/linuxquestions/latest
Feed Title LinuxQuestions.org
Feed Link https://www.linuxquestions.org/questions/
Reply 0 comments