C-style casts to subclass of polymorphic base

  • Thread starter Christopher Benson-Manica
  • Start date
C

Christopher Benson-Manica

Does the following code exhibit undefined behavior?

#include <stdio.h>

class A
{
virtual int quux()=0;
};

class B : public A
{
int quux() {return(1);}
public:
unsigned int foo;
};

class C: public A
{
int quux() {return(0);}
public:
const char *bar;
};

void baz( const A &a )
{
((B*)&a)->foo=3; /* a is a C, not a B */
/* Prints 3, 00000000 */
printf( "%u, %p\n", ((B*)&a)->foo, (void *)dynamic_cast<const B*>(&a)) );
}

int main()
{
C b;
baz( b );
return 0;
}
 
C

Christopher Benson-Manica

Christopher Benson-Manica said:
printf( "%u, %p\n", ((B*)&a)->foo, (void *)dynamic_cast<const B*>(&a)) );
(void *)(dynamic_cast<const B*>(&a))

Sorry about that.
 
D

David Hilsee

Christopher Benson-Manica said:
Does the following code exhibit undefined behavior?

#include <stdio.h>

class A
{
virtual int quux()=0;
};

class B : public A
{
int quux() {return(1);}
public:
unsigned int foo;
};

class C: public A
{
int quux() {return(0);}
public:
const char *bar;
};

void baz( const A &a )
{
((B*)&a)->foo=3; /* a is a C, not a B */
/* Prints 3, 00000000 */
printf( "%u, %p\n", ((B*)&a)->foo, (void *)dynamic_cast<const B*>(&a)) );
}

int main()
{
C b;
baz( b );
return 0;
}

Sutter's GOTW has a similar example that claims that it is not portable.
See http://www.gotw.ca/gotw/076.htm, #3 (The Cheat). Do you really want to
use this code, or are you posing a hypothetical question about undefined
behavior? It should be obvious to most experienced C and C++ programmers
that the code is using a dirty hack. I don't know if anyone has the
patience to track down the exact quote in the standard that states why it is
a hack or invokes undefined behavior.
 
C

Christopher Benson-Manica

David Hilsee said:
See http://www.gotw.ca/gotw/076.htm, #3 (The Cheat). Do you really want to
use this code, or are you posing a hypothetical question about undefined
behavior? It should be obvious to most experienced C and C++ programmers
that the code is using a dirty hack. I don't know if anyone has the
patience to track down the exact quote in the standard that states why it is
a hack or invokes undefined behavior.

I definitely do not want to use the code; I asked because some code
that I am working on that's mostly maintained by my boss blindly uses
a C-style cast to cast a pointer to a base to a particular subclass,
rather than using dynamic_cast and checking for failure. I wanted a
firm basis for telling him that the code is dangerous as written.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,013
Latest member
KatriceSwa

Latest Threads

Top