Re: How to convert Pointer between structs?
* Immortal Nephi:
I am curious. How can you overcome Compiler's error? You define b
and c inside main(). You may want to convert from C::F_C() to B::F_B
() on C::*pC. Can reinterpret_cast keyword be used? If not, can you
replace C::*pC to global scope? It may be easier that B::F_B() can be
invoked inside global scope. Please do not mention static keyword.
Let me know if it is possible.
struct B
{
void F_B() {}
int _B;
The name _B is invalid (it's reserved for the implementation) because it starts
with an underscore followed by uppercase.
};
struct C
{
void F_C() {}
void (C::*pC)();
int _C;
};
int main(void)
{
B b;
C c;
c.pC = &B::F_B; // Error
(c.*(c.pC))();
return 0;
}
First of all, as a novice *don't* use
- goto
- member pointers
- all uppercase names for non-macro things
- macro names that are not all uppercase
- raw pointers where they can be avoided
It seems that you want some code to treat instances of the two classes B and C
in the same way, while they're slightly different on the inside.
This is known as polymorphism.
And C++ offers two main ways to do that: compile time polymorphism (templates),
and run time polymorphism (virtual member functions).
As an example of the latter:
class IntHolder
{
private:
int c_;
public:
IntHolder( int v = 0 ): c_( v ) {}
virtual void f() = 0;
};
class B: public IntHolder
{
public:
B( int v = 0 ): IntHolder( v ) {}
virtual void f() { ... }
};
class C: public IntHolder
{
public:
C( int v = 0 ): IntHolder( v ) {}
virtual void f() { ... }
};
void foo( IntHolder& o ) { o.f(); }
int main()
{
B b;
C c;
foo( b ); foo( c );
}
By the way, which book are you using that doesn't discuss this?
It can be helpful to others to know about that book, to avoid it.
Cheers & hth.,
- Alf