rkb
rkb

Reputation: 11231

Does dynamic_cast behave as a static_cast, if there is not a single virtual function?

In a class hierarchy without any virtual functions, will dynamic_cast behave as a simple static_cast since it doesn't have any information stored for RTTI, or it will give an error?

Upvotes: 2

Views: 293

Answers (1)

vitaut
vitaut

Reputation: 55605

It's easy to check:

class A {};
class B : public A {};

int main(int argc, char **argv) {
  A* a = new B();
  B* b = dynamic_cast<B*>(a);
}

G++ says:

error: cannot dynamic_cast 'a' (of type 'class A*') to type 'class B*' (source type is not polymorphic)

BTW for this kind of questions I find online llvm-gcc demo useful.

Upvotes: 8

Related Questions