473,763 Members | 1,333 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Storing Pointer in a Class Hierarchy

Hi,

As I am interfacing my code in C++ with a scripting language which is
written in C, I need to store pointers to objects in a class hierarchy:

ParentClass *obj1;
obj1 = new ParentClass (...);
... do things with obj1...
STORE_POINTER (scriptObj1, obj1);

DerivedClass *obj2;
obj2 = new DerivedClass (...);
...do things with obj2...
STORE_POINTER (scriptObj2, obj2);

However, when I try to retrieve an object, as I don't know which class the
object belongs to, I always use the base class (in this code segment I
just need the functionalities related to the ParentClass):

ParentClass *objN;
RETRIEVE_POINTE R (scriptObjN, ParentClass, objN);
...do things with objN...

where STORE_POINTER and RETRIEVE_POINTE R are some utility macros provided
by the scripting language.

I ran the code and I got a segmentation fault. I also notice that when
I printed out a pointer and cast it to different classes in the hierarchy,
I got different values:

cout << "pointer as parent = " << (ParentClass*) this << endl;
cout << "pointer as derived = " << (DerivedClass*) this << endl;

So my question is, in C++, is it unsafe to type cast a pointer to a
derived class to a pointer to a base class? (The other way around never
makes sense, of course.) If it is unsafe, what is the best way to solve
the above problem? Thanks.

Regards,

Bill
Jul 22 '05 #1
3 1663
William Djaja Tjokroaminata wrote:
However, when I try to retrieve an object, as I don't know which class the
object belongs to, I always use the base class (in this code segment I
just need the functionalities related to the ParentClass):

ParentClass *objN;
RETRIEVE_POINTE R (scriptObjN, ParentClass, objN);
...do things with objN...

where STORE_POINTER and RETRIEVE_POINTE R are some utility macros provided
by the scripting language.

I ran the code and I got a segmentation fault. I also notice that when
I printed out a pointer and cast it to different classes in the hierarchy,
I got different values:

cout << "pointer as parent = " << (ParentClass*) this << endl;
cout << "pointer as derived = " << (DerivedClass*) this << endl;


Never use a C-style cast.

In your case, if ParentClass contains virtual things,
dynamic_cast<De rivedClass*>(th at) will return NULL if '*that' is not a
DerivedClass.

--
Phlip
http://www.xpsd.org/cgi-bin/wiki?Tes...UserInterfaces
Jul 22 '05 #2

"William Djaja Tjokroaminata" <bi****@y.glue. umd.edu> wrote in message
news:c0******** **@grapevine.wa m.umd.edu...
Hi,

As I am interfacing my code in C++ with a scripting language which is
written in C, I need to store pointers to objects in a class hierarchy:

ParentClass *obj1;
obj1 = new ParentClass (...);
... do things with obj1...
STORE_POINTER (scriptObj1, obj1);

DerivedClass *obj2;
obj2 = new DerivedClass (...);
...do things with obj2...
STORE_POINTER (scriptObj2, obj2);

However, when I try to retrieve an object, as I don't know which class the
object belongs to, I always use the base class (in this code segment I
just need the functionalities related to the ParentClass):

ParentClass *objN;
RETRIEVE_POINTE R (scriptObjN, ParentClass, objN);
...do things with objN...

where STORE_POINTER and RETRIEVE_POINTE R are some utility macros provided
by the scripting language.

I ran the code and I got a segmentation fault. I also notice that when
I printed out a pointer and cast it to different classes in the hierarchy,
I got different values:

cout << "pointer as parent = " << (ParentClass*) this << endl;
cout << "pointer as derived = " << (DerivedClass*) this << endl;

So my question is, in C++, is it unsafe to type cast a pointer to a
derived class to a pointer to a base class?
That is never unsafe, I fact it so safe that you don't need a cast. In fact
its wrong to use a cast.

You should not be using that fact that the pointer value changes as evidence
that the technique is unsafe. Sometimes the pointer changing value is what
is supposed to happen.
(The other way around never
makes sense, of course.)


Never make sense, why not? In C++ one would use dynamic_cast or static_cast
for exactly this purpose.

john
Jul 22 '05 #3
Hi,

Thanks for the reply. Can someone point out how to use static/dynamic
cast correctly in relation with STORE_POINTER and RETRIEVE_POINTE R (which
were written in C)?

Regards,

Bill
=============== =============== =============== =============== =============
Phlip <ph*******@yaho o.com> wrote:
Never use a C-style cast. In your case, if ParentClass contains virtual things,
dynamic_cast<De rivedClass*>(th at) will return NULL if '*that' is not a
DerivedClass.

Jul 22 '05 #4

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

Similar topics

6
7929
by: xsist10 | last post by:
whats the best method. delphi lets you do something very simple ptrMethodFoo : procedure how do you do this in C++?
37
5018
by: Ben | last post by:
Hi, there. Recently I was working on a problem where we want to save generic closures in a data structure (a vector). The closure should work for any data type and any method with pre-defined signature. When developing this lib, I figured that the pointer-to-member-function, although seemingly an attractive solution, does not work well for us.
5
1476
by: Gonçalo Rodrigues | last post by:
Hi all, (note: newbie alert) Suppose you have a hierarchy of objects that you deal with via smart pointers, e.g. something like: template<typename T> class Ref { private:
0
975
by: Gonçalo Rodrigues | last post by:
Hi all, I'm working around with smart pointers mostly as a learning exercise: I have a single-rooted hierarchy with the root class Object. Every Object has a member field count, the number of references to the Object, and a few methods for dealing with reference counts: getCount, incCount, decCount with the obvious meanings. To handle these guys I have made a smart pointer template in the usual way
6
2577
by: Alfonso Morra | last post by:
I have written the following code, to test the concept of storing objects in a vector. I encounter two run time errors: 1). myClass gets destructed when pushed onto the vector 2). Prog throws a "SEGV" when run (presumably - attempt to delete deleted memory. Please take a look and see if you can notice any mistakes I'm making. Basically, I want to store classes of my objects in a vector. I also have three further questions:
41
10055
by: Alexei A. Frounze | last post by:
Seems like, to make sure that a pointer doesn't point to an object/function, NULL (or simply 0) is good enough for both kind of pointers, data pointers and function pointers as per 6.3.2.3: 3 An integer constant expression with the value 0, or such an expression cast to type void *, is called a null pointer constant.55) If a null pointer constant is converted to a pointer type, the resulting pointer, called a null pointer, is guaranteed...
5
3912
by: jason.cipriani | last post by:
There have been some recent threads about casting pointers to and from void* that have me rethinking some of my usual practices. I have a couple of questions. 1. What is the purpose of C++'s static_cast<>? In other words, is there any real difference between statements like (with non-pointer types): double a = 3.4; int b = (int)a; // <--- this
3
1685
by: Ramon F Herrera | last post by:
Newbie alert: I come from C programming, so I still have that frame of mind, but I am trying to "Think in C++". In C this problem would be solved using unions. Hello: Please consider the snippet below. I have some objects which are derived (subclassed?, subtyped?) from simpler ones, in increasing size. There is a linear hierarchy. I need to keep them all in some sort of linked list (perhaps std::vector). I could have several
3
1445
by: Rahul | last post by:
While reading Inside the C++ object model I came through the following paragraph Point3d origin, *ptr = &origin; A) origin.x = 0.0; B) ptr->x = 0.0; The book says "A & B statements performs equivalently if x is a member of a struct, class, single inheritance hierarchy, or multiple inheritance hierarchy" This is because compiler knows the offset of
0
9563
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...
1
9938
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,...
1
7366
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6642
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
5270
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...
0
5406
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3917
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
3523
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2793
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.