views:

62

answers:

1

I have a conversion like this:

Class1 *p1;
Class2 *p2 = new Class2();
p1 = (Class1 *) p2;

Can I override the typecast operator above to return a custom Class1 object pointer? If yes how?

EDIT: My exact problem is that I have code like this:

if (*$1 == ArrayType(AnyType()))
{
    $$ = ((ArrayType *) $1)->getElementsType();
}

Operator == is overloaded so $1 may be of type AnyType *.

+3  A: 

No, you cannot overload conversion operators of non-class types.

What is the actual problem you want to solve? You might want to consider providing conversion operators in the actual classes.

David Rodríguez - dribeas
It's a Bison/Flex project. yylval must be a pointer to a class not an instance of it. I have defined a Type class with subclasses ArrayType and AnyType (which is supposed to equal any Type (sub)class). So sometimes I have a pointer to AnyType and must create an ArrayType pointer from it.
Panayiotis Karabassis