Y
Yu Hu
Hello,
Is it legal (and moral) to assign a method pointer with the proper
prototype to a variable whose type involves the superclass? (Sorry if my
wording of the question is imprecise, I'm not sure what all the right
terminology is.) A code example should make it clear what I'm asking:
class A
{
public:
int Fn1( int x );
// ...
};
typedef int (A::*AMemFn)( int x );
class B : public A
{
public:
int Fn2( int x );
// ...
};
// Assume the methods are defined and the classes are completed elsewhere
AMemFn f = &B::Fn2; // Is this OK?
// Two examples of how I am using f:
B b_obj;
int r = (b_obj.*f)( 5 );
A *a_ptr = new B;
r = (a->(*f))( 5 );
In my code, I know that the type of the object and the class that the
method being stored in the variable agree. It still feels sketchy to me
because it seems like you could screw yourself by making an object of
type A and then calling a method of class B on it, which can cause bad
things to happen.
Visual C++ and g++ permit me to do this, but I wanted to know if this
generally should work.
Is it legal (and moral) to assign a method pointer with the proper
prototype to a variable whose type involves the superclass? (Sorry if my
wording of the question is imprecise, I'm not sure what all the right
terminology is.) A code example should make it clear what I'm asking:
class A
{
public:
int Fn1( int x );
// ...
};
typedef int (A::*AMemFn)( int x );
class B : public A
{
public:
int Fn2( int x );
// ...
};
// Assume the methods are defined and the classes are completed elsewhere
AMemFn f = &B::Fn2; // Is this OK?
// Two examples of how I am using f:
B b_obj;
int r = (b_obj.*f)( 5 );
A *a_ptr = new B;
r = (a->(*f))( 5 );
In my code, I know that the type of the object and the class that the
method being stored in the variable agree. It still feels sketchy to me
because it seems like you could screw yourself by making an object of
type A and then calling a method of class B on it, which can cause bad
things to happen.
Visual C++ and g++ permit me to do this, but I wanted to know if this
generally should work.