typecasting the base class to derived class.

C

cman

#include <stdio.h>

class Base
{
public:
Base()
{
printf("Base()\n");
}
~Base()
{
printf("~Base()\n");
}
};

class Derived:public Base
{
public:
Derived()
{
printf("Derived()\n");
}
void myConst() const
{
printf("Derived's myConst function x=%d",x);
}
~Derived()
{
printf("~Derived()\n");
}
int x;
};

main()
{
Derived *dptr;
dptr=(Derived *)new Base();
dptr->x=10;
dptr->myConst();
delete dptr;
}


In the above code "dptr->myConst()" succeeds without giving any error
on Solaris, but generates an exception when ran on Winodws after
compiling in VC++

My Question is Why does it not fail? since typecasting should not
define x... this call should fail. I replaced "x" with "x[1024]" and
then used the last element in the array above, to isolate the
possiblity of having a fluke. But it still worked !

Thanks.
 
N

Niels Dybdahl

My Question is Why does it not fail?

Pure (un)luck
There are no mechanisms in C++ or the operating systems that guarantee that
you will get an error message, if you address outside the memory area of a
structure. The virtual memory management in the operating systems might in
some cases do it, but never always.
If you use something like BoundsChecker, then you can get a guaranteed error
message on the cost of execution speed.

Niels Dybdahl
 
D

David Harmon

dptr=(Derived *)new Base();

Lots of things that can produce errors are unchecked (except by you.)
But casts surpass them all. When you use a case, that is old C style
cast as above or reinterpret_cast<>, you are assuring the compiler that
you know what you are doing and everything will be all right.

When you cast a base pointer to a derived type it is your responsibility
to first ensure that it actually points to a derived object. If you
fail to do that then all guarantees are voided. See "undefined
behavior".
 
C

cman

The program ran fine on Windows, Solaris and Linux as well.

Also, to verify that the program is not running by chance...
I replaced "int x" with "int x[1024]" and then wrote to the last
element in main() and read back the value from (ie "x[1023]"), but it
still ran fine.

But when I increased the array size to 4096, it crashed...
may be because now it tried to write outside the data segment.

Is this right ?
 

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

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,014
Latest member
BiancaFix3

Latest Threads

Top