Re: Reassign two objects to one pointer?
Immortal Nephi wrote:
I am still working on diamond shape inheritance. I am trying to
figure out how to change one pointer between two objects. I always
tell C++ Compiler to select Center1:: or Center2::. I do not want to
declare one pointer with either derived classes. For example, I want
to stick
B_PTR->Run() instead of B_PTR->Center1::Run(). I help to keep
unmodified code in the function body and I simply need to reassign
pointer. Also, I will need to invoke pointer to member function as
well. Look at main() for example.
You are well advised to seriously rethink your design. What you want is
simply not possible in C++.
<snip>
int main()
{
Bottom b;
Center1* C1_PTR = &b;
Center2* C2_PTR = &b;
Bottom* B_PTR = 0;
B_PTR = static_cast< Bottom* >( C1_PTR );
( B_PTR->*( B_PTR->Run_PTR ) )();
This line is ambiguous, because B_PTR has two accessible members called
Run_PTR. You must explicitly specify if you want the version from
Center1 or from Center2.
B_PTR->Run(); // Invoke Center1::Run()
No. That invokes Bottom::Run.
// B_PTR->Center1::Run(); // I do not want it, but stick B_PTR->Run()
Too bad you don't want it, because it is the easiest way to invoke
Center1::Run when you have a Bottom*.
The only other way is to cast the pointer first to a Center1*:
static_cast<Center1*>(B_PTR)->Run();
// Change pointer between derived classes
B_PTR = static_cast< Bottom* >( C2_PTR );
If you print the value of B_PTR before and after this assignment, you
will notice that both values are identical.
( B_PTR->*( B_PTR->Run_PTR ) )();
B_PTR->Run(); // Invoke Center2::Run()
// B_PTR->Center2::Run(); // I do not want it, but stick B_PTR->Run()
return 0;
}
Bart v Ingen Schenau
--
a.c.l.l.c-c++ FAQ: http://www.comeaucomputing.com/learn/faq
c.l.c FAQ: http://c-faq.com/
c.l.c++ FAQ: http://www.parashift.com/c++-faq-lite/