Overloading cast operator with pointers
Overloading cast operator with pointers
(OP)
Hi everyone - I am trying to overload the cast operator on a class. However, I would like to do it with pointers. For instance, I want:
Class1* var1;
Class2* var2;
var2 = (Class2*)var1;
When the cast happens, I want to execute a chunk of code which will assert that Class1 is actually an instance of Class2. I have seen lots of examples where the actual object cast can be overloaded, but not a pointer to the object.
Any thoughts? Your help is always apprecitated!
-Tim
Class1* var1;
Class2* var2;
var2 = (Class2*)var1;
When the cast happens, I want to execute a chunk of code which will assert that Class1 is actually an instance of Class2. I have seen lots of examples where the actual object cast can be overloaded, but not a pointer to the object.
Any thoughts? Your help is always apprecitated!
-Tim





RE: Overloading cast operator with pointers
var2 = (Class2*)var1;
just insert an additional cast to pointer to void
var2 = (Class2*)((void*)var1);
Most compilers accept this.
Mark
RE: Overloading cast operator with pointers
When you overload the output operator "<<" on a class, for instance, you can tell it to do something different. I want the "cast" operator to do something different in this case. I could easily check in advance to see if var1 was an instance of Class2 and then do the cast as it is noted above, but after doing this 10 or so times, the code gets fairly large and a shorter way of converting would be useful.
If only the compiler supported <dynamic_cast>... Ah, at times Java is the answer...
-Tim
RE: Overloading cast operator with pointers
Here is a simple solution for your problem. This will generate a compilation error if you wan to cast to a wrong type.
For run-time checking use dynamic_cast. (enable RTTI in your compiler in this case!).
Class1
{
};
Class2 : public Class1
{
public:
template<class T> operator T*()
{
return static_cast<T*>(this);
}
};
Class3
{
};
void foo()
{
Class1 *c1 = new Class1();
Class2 *c2 = (Class1*)c1; //OK
Class3 *c3 = (Class3*)c1; //generates a compilation error
}
RE: Overloading cast operator with pointers
RE: Overloading cast operator with pointers
I would like to be able to say:
class2 *ptr2 = (class2*)ptr1;
rather than:
class2 *ptr2 = dynamic_cast<class2*>(ptr1);
and override it with both the dynamic cast and the assert.
However, I can not find a way to override an explicint (or implicit) cast.
zolle69's response would have been just perfect.
(I had to correct one line:
Class2 *c2 = (Class1*)c1; //OK
to
Class2 *c2 = (Class2*)c1; //OK
to get it to compile.)
However:
- it compiles under microsoft,visual c++ 7.0 , with no complaint,
- it runs with no complaint, (It should complain about the cast fo Class3),
- however it never executes the code in the template cast.
---
Has anyone found a way to overide a cast, so I can do checking