[C++] Pointer to function giving error
I have a very simple function pointer that I even got out of a book, but my compiler (dev cpp) is giving me the following errors:
35 C:\Dev-Cpp\main.cpp invalid use of non-static member function `virtual void Mammal::speak()'
35 C:\Dev-Cpp\main.cpp cannot convert `void (Mammal::)()' to `void (Mammal::*)()' in assignment
The code is as follows:
Code:
#include <iostream>
using namespace std;
class Mammal
{
public:
Mammal() { }
virtual ~Mammal() { }
Mammal(const Mammal&) { }
virtual void speak()
{
cout << "Mammal speak\n";
}
};
class Cat: public Mammal
{
public:
Cat() { }
~Cat() { }
Cat(const Cat&) { }
void speak()
{
cout << "Meow\n";
}
};
int main(int argc, char* argv[])
{
Mammal m;
void (Mammal::*pFunc)() = 0;
pFunc = Mammal::speak;
Mammal* ptr = new Cat;
(ptr->*pFunc)();
delete ptr;
}
What exactly am I doing wrong to recieve this error? Everything looks correct?
Re: [C++] Pointer to function giving error
I think you just need to add the 'address of' operator in front of Mammal:
Code:
pFunc = &Mammal::speak;
HTH!
Re: [C++] Pointer to function giving error
You cant use function pointers for member functions (non static) as you do with common functions. It needs a special declaration and you must involve an instance of the object to call them.
Re: [C++] Pointer to function giving error
Quote:
Originally Posted by bilm_ks
You cant use function pointers for member functions (non static) as you do with common functions. It needs a special declaration and you must involve an instance of the object to call them.
My book says you can :)
Quote:
I think you just need to add the 'address of' operator in front of Mammal:
That's it sunburt! I'm thinking certain compilers actually accept the form without the address of operator.
Thanks.
Re: [C++] Pointer to function giving error
Quote:
Originally Posted by bilm_ks
You cant use function pointers for member functions (non static) as you do with common functions. It needs a special declaration and you must involve an instance of the object to call them.
The code System_Error posted has both the special declaration and an instance which invokes the function -- so you're right, but uneccesary :p
I think that when taking the address of a non-static member function, that the & is necessary. I know that with regular (non-class) functions, the & is optional.
Re: [C++] Pointer to function giving error
Correct. Basically, the form without the & was kept for C compatibility, but disliked, so when it came to member functions, where C compatibility was not an issue, so the & was made mandatory.