Suppose I have a pointer of type *Foo. I want to pass it to a function that expects a pointer of type *Bar, so I have to create a cast between those. How do I do this? I know I can create a cast to Foo using constructors, but how about *Foo?
#include <iostream>
typedefint Foo;
typedefunsignedint Bar;
void Func1(Foo *f)
{
std::cout << *f << std::endl;
}
void Func2(Bar *b)
{
std::cout << *b << std::endl;
}
int main()
{
Bar *B = new Bar;
*B = 123;
Foo *F = new Foo;
*F = -789; // note this int* is cast to unsigned int*
Func1(reinterpret_cast<Foo*>(B));
delete B;
Func2(reinterpret_cast<Bar*>(F)); // note what happened when we reinterpreted the type and tried to use it... sometimes unexpected things occur
delete F;
return 0;
}
Suppose I have a pointer of type *Foo. I want to pass it to a function that expects a pointer of type *Bar, so I have to create a cast between those. How do I do this? I know I can create a cast to Foo using constructors, but how about *Foo?
The trouble with describing things in abstract terms like Foo & Bar is that there is an implication of telling us how to do it, rather than describing then asking for a solution. In other words you are asking how to do a solution that came from your interpretation of the problem. If we saw an actual real life scenario, we might come up with a completely different and much better solution. For example, one solution might possibly be polymorphism. If that is the case, there may be no need for any casting, and there could be other advantages as well. There could be other solutions as well: Design Patterns, template code etcetera.
I am trying to implement a Splay Tree, or a binary search tree in general. I have two classes: TNode and TTree. TTree consists of a pointer to TNode named root and other member functions.
The thing is sometimes I want to do something to a subtree (which is a node) rather than the tree itself, so I want to convert the node to a tree to be able to use its member functions. And because I am working on pointers (pointer to node and pointer to tree), I need to convert the pointers instead.
In other words, implement operations that may apply to whole trees or to subtress in terms of the nodes, and add an overload for the whole tree that just calls the actual implementation and passes the root node.