top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

dynamic_cast from a const class in C++

0 votes
264 views

Does the below code look like valid C++, or is it a G++ bug? 5.2.7 has the dynamic_cast operator shall not cast away constness (5.2.11).

The other compilers I could check quickly (clang, icc, msvc) all reject the code, GCCs 3.3, 4.6, 4.7 and 4.8 accept the code.

class A {
};

class B : public A {
};

int main() {
 A* a;
 B* b = new B();
 a = dynamic_cast(b);
 return 0;
}
posted Jun 11, 2013 by anonymous

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

0 votes

You aren't casting *away* const-ness, you are adding const-ness (and then discarding it when you assign to A - which should be an error).

Now if you had done:

int main() {
 A* a;
 const B* b = new B();
 a = dynamic_cast(b);
 return 0;
 }

Then you'd be casting away const-ness.

answer Jun 11, 2013 by anonymous
...