473,783 Members | 2,363 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

typecasting the base class to derived class.

#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("~Derive d()\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.
Jul 22 '05 #1
3 3499
> 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
Jul 22 '05 #2
On 20 Feb 2004 03:51:14 -0800 in comp.lang.c++, co*********@yah oo.com
(cman) was alleged to have written:
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_cas t<>, 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".

Jul 22 '05 #3
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 ?
Jul 22 '05 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
2040
by: Gabriel Genellina | last post by:
Hi In the following code sample, I have: - a Worker class, which could have a lot of methods and attributes. In particular, it has a 'bar' attribute. This class can be modified as needed. - a Base class (old-style) which defines a default class attribute 'bar' too. I can't modify the source code of this class. Note that Workes does not inherit from Base. - a Derived class which must inherit from Base and is a wrapper around Worker: it...
3
8186
by: Kapil Khosla | last post by:
Hi, I have been trying to understand this concept for quite sometime now somehow I am missing some vital point. I am new to Object Oriented Programming so maybe thats the reason. I want to understand what is typecasting in C++. Say I have a Base class and a Derived class, I have a pointer to an object to each. Base *ba = new Base; Derived *de = new Derived;
1
4344
by: Dave | last post by:
Hello NG, Regarding access-declarations and member using-declarations as used to change the access level of an inherited base member... Two things need to be considered when determining an inherited base member's access level in the derived class: its access level in the base class and the type of inheritance (public, protected, or private). After this determination is made, the following possibilities exist for manually changing the...
10
3334
by: Bhan | last post by:
Using Ptr of derived class to point to base class and viceversa class base { .... } class derived : public base { .... }
5
3164
by: Andy | last post by:
Hi all, I have a site with the following architecture: Common.Web.dll - Contains a CommonPageBase class which inherits System.Web.UI.Page myadd.dll - Contains PageBase which inherits CommonPageBase - Contains myPage which inherits PageBase Each of these classes overrides OnInit and ties an event handler
4
5247
by: Jeff | last post by:
The derived class below passes a reference to an object in its own class to its base calss constructor. The code compiles and will run successfully as long as the base class constructor does not attempt to access the object -- since m_object is not actually created and initizialized until after the base constructor has been called. Any thoughts on the practice below? class Base { public:
6
2501
by: Taran | last post by:
Hi All, I tried something with the C++ I know and some things just seem strange. consider: #include <iostream> using namespace std;
5
2625
by: Dennis Jones | last post by:
Hello, I have a couple of classes that look something like this: class RecordBase { }; class RecordDerived : public RecordBase {
2
2413
by: cmonthenet | last post by:
Hello, I searched for an answer to my question and found similar posts, but none that quite addressed the issue I am trying to resolve. Essentially, it seems like I need something like a virtual static function (which I know is illegal), but, is there a way to provide something similar? The class that is the target of my inquiry is a template class that interfaces to one of several derived classes through a pointer to a base class. The...
0
9643
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10147
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10081
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9946
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8968
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6735
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5378
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4044
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2875
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.