views:

83

answers:

1

Is there a way in C++ to construct your class such that given a pointer to your class you can instruct dynamic_cast<>() how to cast to another class for which you are wrapping the implementation? Would operator cast do the trick? Imagine I have an Abstract interface base class and derive a concreteA from this as well as concreteB, but concreteB wraps the interface to an object of type concreteA. If I get a request to cast to concreteA from concreteA, I'd like it to work:

class Abstract {
public:
  virtual void interface() = 0;

};

class concreteA : public Abstract {
public:
  virtual void interface();

};

class concreteB : public Abstract {
public:
  concreteB(concreteA &underlying)
    : _underlying(&underlying) {
  }
  virtual void interface();

  operator concreteA*() {
    return _underlying;
  }

private:
  concreteA *_underlying;

};

void
myTest() {
  concreteA myClassA;
  concreteB myClassB(myClassA);
  Abstract *abstract = &myClassB;
  concreteA *underlying = dynamic_cast<concreteA *>(abstract);
}
+4  A: 

No. A dynamic cast is telling the compiler "I don't want to change this object at all, I just want to attempt to look at it as if it were this other type, but don't change it. If you have to change it, return NULL or throw an exception.". Dynamic cast is not going to attempt to perform any such conversions on your behalf. For that, you need static_cast or boost::lexical_cast.

This is because the cast operator can either:

  • Reinterpret an existing object in a new way without changing it
  • Change an object in some way in order to coerce it to be another type, such as int -> short, or double -> int.

and a single cast invocation can only do one of these, not both.

For more information on the "dual" nature of the cast operator, you can see this article by Eric Lippert, which is aimed at C# but mostly applies to C++ as well.

Specifically, you can see § 5.2.7 in the most recent C++0x draft -- that behavior is not changed from C++03.

Billy ONeal