Scenario:
I have a base class called "BaseCls", and two derived classes called
"DerCls1" and "DerCls2"
I declare a variable -
BaseCls *MyClassObj;
I have some code -
If( Condition )
{
MyClassObj = new DerCls1;
} else {
MyClassObj = new DerCls2;
}
How can I tell if MyClassObj is pointing to a DerCls1 or DerCls2
object?
Thanks in advance... 5 2071
"zRaze" <ab***@msn.co m> wrote in message
news:o2******** *************** *********@4ax.c om... Scenario: I have a base class called "BaseCls", and two derived classes called "DerCls1" and "DerCls2"
I declare a variable - BaseCls *MyClassObj;
I have some code -
If( Condition ) { MyClassObj = new DerCls1; } else { MyClassObj = new DerCls2; }
How can I tell if MyClassObj is pointing to a DerCls1 or DerCls2 object?
One way would be to have a virtual function in your base class, that
returns some info that it is the base class. The derived classes are
required to overload it and return info depending on what class they are.
Another way is to use dynamic_cast. If you cast the base class pointer
to the wrong derived class pointer type, you will get a null pointer.
Personally, I would prefer the former method, even tho you have the
disadvantage of requiring all derived classes to overload that function. If
the base class is (or can be) abstract anyway, you could make that make the
'info' function pure virtual even.
hth
--
jb
(replace y with x if you want to reply by e-mail)
Thanks!
On Sat, 11 Oct 2003 18:05:13 +0200, "Jakob Bieling" <ne*****@gmy.ne t>
wrote: "zRaze" <ab***@msn.co m> wrote in message news:o2******* *************** **********@4ax. com... Scenario: I have a base class called "BaseCls", and two derived classes called "DerCls1" and "DerCls2"
I declare a variable - BaseCls *MyClassObj;
I have some code -
If( Condition ) { MyClassObj = new DerCls1; } else { MyClassObj = new DerCls2; }
How can I tell if MyClassObj is pointing to a DerCls1 or DerCls2 object?
One way would be to have a virtual function in your base class, that returns some info that it is the base class. The derived classes are required to overload it and return info depending on what class they are.
Another way is to use dynamic_cast. If you cast the base class pointer to the wrong derived class pointer type, you will get a null pointer.
Personally, I would prefer the former method, even tho you have the disadvantage of requiring all derived classes to overload that function. If the base class is (or can be) abstract anyway, you could make that make the 'info' function pure virtual even.
hth
"zRaze" <ab***@msn.co m> wrote in message
news:o2******** *************** *********@4ax.c om... Scenario: I have a base class called "BaseCls", and two derived classes called "DerCls1" and "DerCls2"
I declare a variable - BaseCls *MyClassObj;
I have some code -
If( Condition ) { MyClassObj = new DerCls1; } else { MyClassObj = new DerCls2; }
How can I tell if MyClassObj is pointing to a DerCls1 or DerCls2 object?
Thanks in advance...
If you have to make that distinction you probably have a poor design. When
you have a pointer to a base class which really points to a derived class,
you are using polymorphism. As Jakob implied, the best way to deal with
polymorphism is to call a virtual function which does the right thing no
matter what type it is. This scheme is efficient and maintainable. (For
instance it would be easy to add a DerCls3 later.) If it is impossible
because you can't implement any such virtual function then maybe
polymorphism was the wrong approach in the first place.
A couple of other points: you should probably put a do-nothing virtual
destructor in the base class:
virtual ~BaseCls() {}
to make sure possible destructors in derived classes are called properly.
Also, whenever you use new() you must use delete() to avoid a memory leak
and you must use it only once to avoid undefined behaviour. This can be a
source of problems. Consider using a reference counted smart pointer instead
of a raw pointer for MyClassObj:
typedef boost::shared_p tr<BaseCls> BaseClsPtr;
MyClassObj = BaseClsPtr(new DerCls1);
It will automatically delete the object when the pointer goes out of scope
so you don't have to worry about it.You can get such a pointer at www.boost.org
Good luck.
--
Cy http://home.rochester.rr.com/cyhome/
Basically, the reason I need to know what class a pointer points to is
because I have a 2 dimensional array of pointers (it's a map)
and my classes are the landmarks etc. (Road, open space etc.)
So therefore, I don't have the problem with adding new classes, but
when I come do save the map to disk, I need to be able to tell what is
on that tile for when reloading.
I have now got a new method of this. I had a function that returned a
graphic handle (for drawing on the screen), however, I was having
problems (which I thought was related, but wasn't) so I changed it to
return an enum value which gets linked to the graphic, and I'm just
going to use that enum value...
Thanks for your help tho...
On Sun, 12 Oct 2003 02:47:54 GMT, "Cy Edmunds"
<ce******@spaml ess.rochester.r r.com> wrote: "zRaze" <ab***@msn.co m> wrote in message news:o2******* *************** **********@4ax. com... Scenario: I have a base class called "BaseCls", and two derived classes called "DerCls1" and "DerCls2"
I declare a variable - BaseCls *MyClassObj;
I have some code -
If( Condition ) { MyClassObj = new DerCls1; } else { MyClassObj = new DerCls2; }
How can I tell if MyClassObj is pointing to a DerCls1 or DerCls2 object?
Thanks in advance...
If you have to make that distinction you probably have a poor design. When you have a pointer to a base class which really points to a derived class, you are using polymorphism. As Jakob implied, the best way to deal with polymorphism is to call a virtual function which does the right thing no matter what type it is. This scheme is efficient and maintainable. (For instance it would be easy to add a DerCls3 later.) If it is impossible because you can't implement any such virtual function then maybe polymorphism was the wrong approach in the first place.
A couple of other points: you should probably put a do-nothing virtual destructor in the base class:
virtual ~BaseCls() {}
to make sure possible destructors in derived classes are called properly. Also, whenever you use new() you must use delete() to avoid a memory leak and you must use it only once to avoid undefined behaviour. This can be a source of problems. Consider using a reference counted smart pointer instead of a raw pointer for MyClassObj:
typedef boost::shared_p tr<BaseCls> BaseClsPtr;
MyClassObj = BaseClsPtr(new DerCls1);
It will automatically delete the object when the pointer goes out of scope so you don't have to worry about it.You can get such a pointer at
www.boost.org
Good luck.
"zRaze" <ab***@msn.co m> wrote in message
news:o2******** *************** *********@4ax.c om... Scenario: I have a base class called "BaseCls", and two derived classes called "DerCls1" and "DerCls2"
I declare a variable - BaseCls *MyClassObj;
I have some code -
If( Condition ) { MyClassObj = new DerCls1; } else { MyClassObj = new DerCls2; }
How can I tell if MyClassObj is pointing to a DerCls1 or DerCls2 object?
This is not a hard and fast rule, but one of the basic principles OO code
such as that is you're not *supposed* to know. And you're supposed to write
your code in such a way that the code doesn't care either. This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: |
last post by:
I have this class
-------------
class Component {
/*class*/ Data *d;
/*class*/ Draw *a;
};
-------------
from "Component" derive classes like "TextBox", "Button", "Label", "ComboBox" etc
from "Draw" derive classes like "TextBoxDraw", "ButtonDraw", "LabelDraw", "ComboBoxDraw" etc
from "Data" derive classes like "TextBoxData", "ButtonData", "LabelData", "ComboBoxData" etc
|
by: Jack |
last post by:
Hello
I have a library of calculationally intensive classes that is used both by a
GUI based authoring application and by a simpler non-interactive rendering
application. Both of these applications need to serialise the classes
to/from the same files but only the GUI app needs the full range of class
methods.
Now, the rendering app needs to be ported to multiple OS's but the GUI
doesn't. In order to reduce the time/cost of porting I'd...
|
by: John J |
last post by:
I requested help with some code in a previous thread, as requested in the
feedback, below are the .cpp and .h files for all three classes (Entry, Race
and Yacht). The three classes are all ossociated through pointers. Objects
are created and called in a main as follows: (I apologise for the excess of
white space, unfortunately this occurs when I cut and paste from my
compiler)
Race r1(1, "23/12/03");
Race r2(2, "24/12/03");
|
by: Sean J. Fraley |
last post by:
This code illustrates what I'm confused about:
template<typename T>
class foo
{
public:
template<typename U>
void
fooFunction(const foo<U>& x)
{
|
by: Bilgehan.Balban |
last post by:
Hi,
I am currently brushing up my c++ knowledge and I would like to ask you
about the differences between classes and C structs, in the
function/method perspective.
1) Is it correct to say that, a structure definition that includes
function pointers only defines the function prototypes to be used with
them, but not the actual implementations, whereas in C++, member
functions cannot be changed *unless* virtual functions are used, or the
| |
by: alternativa |
last post by:
Hello,
I have a few questions concerning classes.
1)
Why some people use default constructos, i.e constructors with no
parameters? To me it doesn't make any sense, is there something I
should know? For example, I'd declare a class in a following way:
class Sample {
int number;
string title;
|
by: ivan.leben |
last post by:
I want to write a Mesh class using half-edges. This class uses three
other classes: Vertex, HalfEdge and Face. These classes should be
linked properly in the process of building up the mesh by calling Mesh
class functions. Let's say they point to each other like this:
class Vertex {
HalfEdge *edge;
};
class HalfEdge {
Vertex* vert;
|
by: weaknessforcats |
last post by:
Handle Classes
Handle classes, also called Envelope or Cheshire Cat classes, are part of the Bridge design pattern. The objective of the Bridge pattern is to separate the abstraction from the implementation so the two can vary independently.
Handle classes usually contain a pointer to the object implementation. The Handle object is used rather than the implemented object. This leaves the implemented object free to change without affecting...
|
by: bgold |
last post by:
Hey. I have a base class (SPRITE), and using this base class I have
derived a large number of derived classes (PERSON, BULLET, MISSILE,
etc.). Now, at a certain point in my program, I have a pair of
pointers, where each is a pointer to the base class (each is a SPRITE
*). I know that each of these pointers actually points to one of the
derived classes, even though the type of the pointer is SPRITE *, but
I don't know which derived class it...
|
by: ademirzanetti |
last post by:
Hi there !!!
I would like to listen your opinions about inherit from a STL class
like list. For example, do you think it is a good approach if I
inherit from list to create something like "myList" as in the example
below ?
#include "Sector.h"
using namespace boost;
|
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...
| |
by: Hystou |
last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it.
First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
|
by: Oralloy |
last post by:
Hello folks,
I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>".
The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed.
This is as boiled down as I can make it.
Here is my compilation command:
g++-12 -std=c++20 -Wnarrowing bit_field.cpp
Here is the code in...
|
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...
|
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,...
|
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...
|
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...
| |
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();...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
| |