0

The following statement gives me compiler error as a surprise to me:

BaseClass& base;

if (((const AClass*) ptr = dynamic_cast<const AClass*> (&base)) != NULL)
{
  ...
}

GCC 4.1.2 says ptr isn't defined as an error. However an ordinary defintion and assignment would work. Such as

if (const int* ptr = f())

So what makes it not working for the above code segment?

No this isn't a duplication of the other thread as I have pointed out the simple case works but not such a case. If you think it's a duplication can you at least point out why the above one doesn't work then.

Alex Suo
  • 2,977
  • 1
  • 14
  • 22
  • Possible duplicate of [Declaring and initializing a variable in a Conditional or Control statement in C++](http://stackoverflow.com/questions/1516919/declaring-and-initializing-a-variable-in-a-conditional-or-control-statement-in-c) – Rostislav Oct 20 '15 at 01:20
  • 1
    Maybe you meant `if ( const AClass *ptr = dynamic_cast(&base) )` – M.M Oct 20 '15 at 01:25
  • @M.M Tried all such variants but still same error. – Alex Suo Oct 20 '15 at 01:30
  • @AlexSuo try exactly what I wrote, not some variants. [See it working](http://goo.gl/WNYxeT) – M.M Oct 20 '15 at 01:32
  • Alright I got a simple mistake then. Thanks. – Alex Suo Oct 20 '15 at 05:49

1 Answers1

1

This

(const AClass*) ptr

is a cast of ptr to type const AClass*, not a declaration. If you haven't declared ptr already then you'll get the error you mentioned.

Adam
  • 16,808
  • 7
  • 52
  • 98
  • 1
    If you had declared `ptr` already it's still an error because the result of the cast is an rvalue, which cannot be assigned to. – M.M Oct 20 '15 at 01:24