N
none
Hi,
I have a base class with a pointer-to-member function
variable. Then I have a derived class that needs to
use that variable to call a member function (with the
same arguments and return value type) in the derived
class. I know in Visual C++ you can just cast the
pointer to member function of the derived class to
that of the base class and it will work, but is this
legal by C++ standards?
Thanks for any replies,
steve
Here's a sample source.
#include<iostream>
using namespace std;
class base {
protected :
// pointer to member function variable
typedef void (base::*function)(void);
function ptr;
public :
// call the member function addressed by ptr
virtual void CallFunction(void) { (this->*ptr)(); }
public :
// possible functions to call
virtual void Function1(void) {
cout << "Calling base::Function1..." << endl;
}
virtual void Function2(void) {
cout << "Calling base::Function2..." << endl;
}
public :
base() { ptr = &base::Function1; }
virtual ~base() { ptr = 0 };
};
class derived : public base {
public :
void Function1(void) {
cout << "Calling derived::Function1..." << endl;
}
void Function2(void) {
cout << "Calling derived::Function2..." << endl;
}
public :
derived() {
// must cast member to base type, this legal?
ptr = (function)&derived::Function1;
}
~derived() {}
};
int main()
{
derived d;
d.CallFunction();
return 0;
}
I have a base class with a pointer-to-member function
variable. Then I have a derived class that needs to
use that variable to call a member function (with the
same arguments and return value type) in the derived
class. I know in Visual C++ you can just cast the
pointer to member function of the derived class to
that of the base class and it will work, but is this
legal by C++ standards?
Thanks for any replies,
steve
Here's a sample source.
#include<iostream>
using namespace std;
class base {
protected :
// pointer to member function variable
typedef void (base::*function)(void);
function ptr;
public :
// call the member function addressed by ptr
virtual void CallFunction(void) { (this->*ptr)(); }
public :
// possible functions to call
virtual void Function1(void) {
cout << "Calling base::Function1..." << endl;
}
virtual void Function2(void) {
cout << "Calling base::Function2..." << endl;
}
public :
base() { ptr = &base::Function1; }
virtual ~base() { ptr = 0 };
};
class derived : public base {
public :
void Function1(void) {
cout << "Calling derived::Function1..." << endl;
}
void Function2(void) {
cout << "Calling derived::Function2..." << endl;
}
public :
derived() {
// must cast member to base type, this legal?
ptr = (function)&derived::Function1;
}
~derived() {}
};
int main()
{
derived d;
d.CallFunction();
return 0;
}