473,915 Members | 7,703 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Base or deruved object?

If I have a base class and several possible derived classes, and I have
a pointer to the base class, what's the best way of determining whether
the pointer is pointing to a base class or to a derived class?

The classes have virtual functions, so I could use a dynamic_cast. Is
there much overhead associated with this?

Alternatively I could have an instance variable in the base class which
derived classes are required to set, or a virtual function which
derived classes are required to override. This puts a burden on
developers of derived classes.

Any other options? Which is best?

--
Simon Elliott http://www.ctsn.co.uk
Jul 22 '05 #1
9 1691
Simon Elliott wrote:
If I have a base class and several possible derived classes, and I have
a pointer to the base class, what's the best way of determining whether
the pointer is pointing to a base class or to a derived class?
The best way is not to do it.

The classes have virtual functions, so I could use a dynamic_cast. Is
there much overhead associated with this?
There is some. Whenever you're concerned with performance, you need to
test it. Nobody will tell you what it's going to be except a profiler.
Alternatively I could have an instance variable in the base class which
derived classes are required to set, or a virtual function which
derived classes are required to override. This puts a burden on
developers of derived classes.

Any other options? Which is best?


The best is to design your program so that you don't need to try to know
what derived class object it is.

V
Jul 22 '05 #2
In message <41************ ***********@new s.gradwell.net> , Simon Elliott
<Si***@at.ctsn. co.uk.invalid> writes
If I have a base class and several possible derived classes, and I have
a pointer to the base class, what's the best way of determining whether
the pointer is pointing to a base class or to a derived class?

The classes have virtual functions, so I could use a dynamic_cast. Is
there much overhead associated with this?
Possibly. (AIUI at least one compiler out there does something
equivalent to a string comparison.) But it's a clear statement of your
true intent, so I'd use that unless and until profiling indicates that
you really have a performance problem.

Alternativel y I could have an instance variable in the base class which
derived classes are required to set,
Ugh. Just Say No to metadata.
or a virtual function which
derived classes are required to override. This puts a burden on
developers of derived classes.

Any other options?
You could provide the override once and for all in a derived class of
your own, and require developers to inherit from that instead of the
real base.
Which is best?


--
Richard Herring
Jul 22 '05 #3
Simon Elliott wrote:

If I have a base class and several possible derived classes, and I have
a pointer to the base class, what's the best way of determining whether
the pointer is pointing to a base class or to a derived class?

The classes have virtual functions, so I could use a dynamic_cast. Is
there much overhead associated with this?

Alternatively I could have an instance variable in the base class which
derived classes are required to set, or a virtual function which
derived classes are required to override. This puts a burden on
developers of derived classes.

Any other options? Which is best?


Well

If a question like that arises, then the first thing we need
to ask is: Why do you want to do this?
The reason for this quesiton is, that almost always you are attempting
the wrong thing:
Instead of figuring out which class it is exactly and depending on the
exact type, you should instroduce a virtual function and just call that
instead.

Having said that: dynamic_cast is a possible solution. Certainly better
then having an instance variable. Why? You already figured it out: Everything
the compiler can do for you automatically is always better then your own
invention.

--
Karl Heinz Buchegger
kb******@gascad .at
Jul 22 '05 #4
Simon Elliott wrote:
If I have a base class and several possible derived classes, and I have
a pointer to the base class, what's the best way of determining whether
the pointer is pointing to a base class or to a derived class?

The classes have virtual functions, so I could use a dynamic_cast. Is
there much overhead associated with this?

You can also use typeid.

The real question is why do you need to know. It's usually the sign
of a bad design for something to have to ask what the type of something
is. Usually, anything that acts "differentl y" for different types
is implemented in virutal functions in the types.
Jul 22 '05 #5
"Simon Elliott" <Simon at ctsn.co.uk> wrote in message
news:41******** *************** @news.gradwell. net...
If I have a base class and several possible derived classes, and I have
a pointer to the base class, what's the best way of determining whether
the pointer is pointing to a base class or to a derived class?
The whole point of polymorphism is to obviate such a need.
If you see this need, I recommend that you reconsider your
design.

The classes have virtual functions, so I could use a dynamic_cast. Is
there much overhead associated with this?
Usually yes.

Alternatively I could have an instance variable in the base class which
derived classes are required to set, or a virtual function which
derived classes are required to override. This puts a burden on
developers of derived classes.

Any other options? Which is best?


Take a few steps back and look at the goals and design
of your application. (State them, and perhaps you'll receive
some ideas).

-Mike
Jul 22 '05 #6
Ok Guys,
on the same thread
I'm writing a Game engine, which performs collision detection.
I want to sepate the collision boundings libaray from the main game engine
and load it as a library.
If simplified this example but it illustrates the point.... :-)

So i declare an abstract base class ( & function ):

///////////////////////////////////////////////////
Bounding & Collision Libaray

//Boundings.h ( only file #include'd by the engine)
///////////////////////
class BoundingObject
{
public:
virtual int GetShape() =0;
};

BoundingObject* CreateBoundingO bject( vector<Triangle s>& tris);
bool GetCollision(Bo undingObject* b1,BoundingObje ct* b2);

//Boundings.cpp
////////////////////////////////
#define B_SPHERE 1
#define B_BOX 2
#define B_TRIANGLE 3
class BoundingSphere : public BoundingObject
{
// specific data
virtual int GetShape() { return B_SPHERE; }
};

class BoundingBox : public BoundingObject
{
// specific data
virtual int GetShape() { return B_BOX; }
};

class BoundingTriangl e : public BoundingObject
{
// specific data
virtual int GetShape() { return B_TRIANGLE; }
};

bool IsCollisionSphe reSphere(Boundi ngSphere* s1,BoundingSphe re* s2);
bool IsCollisionSphe reBox(BoundingS phere* s1,BoundingBox* s2);
bool IsCollisionSphe reTriangle(Boun dingSphere* s1,BoundingTria ngle* s2);
bool GetCollision(Bo undingObject* b1,BoundingObje ct* b2)
{
if( b1.GetShape() == B_SPHERE)
{
if( b1.GetShape() == B_SPHERE) return IsCollisionSphe reSphere(
static_cast<Bou ndingSphere*> b1,

static_cast<Bou ndingSphere*> b2 );

if( b2.GetShape() == B_BOX ) return
IsCollisionSphe reBox( static_cast<Bou ndingSphere*> b1,

static_cast<Bou ndingBox*> b2 );
//etc....
}
//etc

}

//End Bounding & Collision Library
/////////////////////////////////////////////////////////

Then in my game engine:

class object
{
public:
BoundingObject* pBoundingObject ;
vector<Triangle > triData;
};

in the game.....
object* pObj1 = new Obj;
// Some specific code.... //
pObj1->pBoundingObjec t = BoundingObject* CreateBoundingO bject(
pObj->triData ) ;

object* pObj2 = new Obj;
// Some specific code.... //
pObj2->pBoundingObjec t = BoundingObject* CreateBoundingO bject(
pObj->triData ) ;

bool IsCol = IsCollision(pOb j1,pObj2);
the idea is that the engine need not know how the objects are being bounded,
but the comparisions between each type of object can be optimised in the
bounding library. But it is horribly ugly. I can't even use enums for the
Bounding types as adding different bounding types would mean a recompile for
the engine!
Any thoughts??
Mike



"Victor Bazarov" <v.********@com Acast.net> wrote in message
news:Tj******** ********@newsre ad1.dllstx09.us .to.verio.net.. .
Simon Elliott wrote:
If I have a base class and several possible derived classes, and I have
a pointer to the base class, what's the best way of determining whether
the pointer is pointing to a base class or to a derived class?


The best way is not to do it.

The classes have virtual functions, so I could use a dynamic_cast. Is
there much overhead associated with this?


There is some. Whenever you're concerned with performance, you need to
test it. Nobody will tell you what it's going to be except a profiler.
Alternatively I could have an instance variable in the base class which
derived classes are required to set, or a virtual function which
derived classes are required to override. This puts a burden on
developers of derived classes.

Any other options? Which is best?


The best is to design your program so that you don't need to try to know
what derived class object it is.

V

Jul 22 '05 #7
Ignore this thread, i started a new one

"Michael" <sl***********@ hotmail.com> wrote in message
news:ck******** **@hercules.bti nternet.com...
Ok Guys,
on the same thread
I'm writing a Game engine, which performs collision detection.
I want to sepate the collision boundings libaray from the main game engine and load it as a library.
If simplified this example but it illustrates the point.... :-)

So i declare an abstract base class ( & function ):

///////////////////////////////////////////////////
Bounding & Collision Libaray

//Boundings.h ( only file #include'd by the engine)
///////////////////////
class BoundingObject
{
public:
virtual int GetShape() =0;
};

BoundingObject* CreateBoundingO bject( vector<Triangle s>& tris);
bool GetCollision(Bo undingObject* b1,BoundingObje ct* b2);

//Boundings.cpp
////////////////////////////////
#define B_SPHERE 1
#define B_BOX 2
#define B_TRIANGLE 3
class BoundingSphere : public BoundingObject
{
// specific data
virtual int GetShape() { return B_SPHERE; }
};

class BoundingBox : public BoundingObject
{
// specific data
virtual int GetShape() { return B_BOX; }
};

class BoundingTriangl e : public BoundingObject
{
// specific data
virtual int GetShape() { return B_TRIANGLE; }
};

bool IsCollisionSphe reSphere(Boundi ngSphere* s1,BoundingSphe re* s2);
bool IsCollisionSphe reBox(BoundingS phere* s1,BoundingBox* s2);
bool IsCollisionSphe reTriangle(Boun dingSphere* s1,BoundingTria ngle* s2);
bool GetCollision(Bo undingObject* b1,BoundingObje ct* b2)
{
if( b1.GetShape() == B_SPHERE)
{
if( b1.GetShape() == B_SPHERE) return IsCollisionSphe reSphere(
static_cast<Bou ndingSphere*> b1,

static_cast<Bou ndingSphere*> b2 );

if( b2.GetShape() == B_BOX ) return
IsCollisionSphe reBox( static_cast<Bou ndingSphere*> b1,

static_cast<Bou ndingBox*> b2 );
//etc....
}
//etc

}

//End Bounding & Collision Library
/////////////////////////////////////////////////////////

Then in my game engine:

class object
{
public:
BoundingObject* pBoundingObject ;
vector<Triangle > triData;
};

in the game.....
object* pObj1 = new Obj;
// Some specific code.... //
pObj1->pBoundingObjec t = BoundingObject* CreateBoundingO bject(
pObj->triData ) ;

object* pObj2 = new Obj;
// Some specific code.... //
pObj2->pBoundingObjec t = BoundingObject* CreateBoundingO bject(
pObj->triData ) ;

bool IsCol = IsCollision(pOb j1,pObj2);
the idea is that the engine need not know how the objects are being bounded, but the comparisions between each type of object can be optimised in the
bounding library. But it is horribly ugly. I can't even use enums for the
Bounding types as adding different bounding types would mean a recompile for the engine!
Any thoughts??
Mike



"Victor Bazarov" <v.********@com Acast.net> wrote in message
news:Tj******** ********@newsre ad1.dllstx09.us .to.verio.net.. .
Simon Elliott wrote:
If I have a base class and several possible derived classes, and I have a pointer to the base class, what's the best way of determining whether the pointer is pointing to a base class or to a derived class?


The best way is not to do it.

The classes have virtual functions, so I could use a dynamic_cast. Is
there much overhead associated with this?


There is some. Whenever you're concerned with performance, you need to
test it. Nobody will tell you what it's going to be except a profiler.
Alternatively I could have an instance variable in the base class which derived classes are required to set, or a virtual function which
derived classes are required to override. This puts a burden on
developers of derived classes.

Any other options? Which is best?


The best is to design your program so that you don't need to try to know
what derived class object it is.

V


Jul 22 '05 #8
On 15/10/2004, Mike Wahler wrote:
Take a few steps back and look at the goals and design
of your application. (State them, and perhaps you'll receive
some ideas).


The only point where I might want to do this is when I need to create
and destroy objects. Consider something along these lines (unchecked):

Let's say we have a class fooBase and two classes publicly derived
from fooBase: fooDerived1 and fooDerived2. I have a fooFactory class
which creates the correct foo class depending on some given criteria.
class bar
{
private:
foo* foo_;
public:
bar():foo_(0){}
ChangeFoo(int fooType)
{
delete foo_;
foo_ = fooFactory::Ins tance().CreateI nstance(fooType );
}
DoStuffToFoo(in t someArg)
{
foo_->DoStuff(someAr g);
}
};

OK so far (so long as the user remembers to call bar::ChangeFoo( )
before calling bar::DoStuffToF oo(); in real life we probably wouldn't
want something this unsafe.)

The user calls bar::ChangeFoo( ) which sets up foo_ to point to either
fooDerived1 or fooDerived2. The user calls bar::DoStuffToF oo() which
calls the virtual function DoStuff() which is routed to fooDerived1 or
fooDerived2 as applicable.

But suppose the construction of a fooDerived1 or fooDerived2 was a
nontrivial exercise, and further suppose that a new fooDerived1 or
fooDerived2 is only required when the type changes (ie a call to
ChangeFoo need not result in a pristine new fooDerived1 or
fooDerived2). And let's say that classes derived from fooBase need lots
of memory, or access a unique resource, so that we can't have more than
one existing at any one time.

In this case we might want to know what type of foo we need, and what
type of foo we've already got, to avoid having to destroy and recreate
a foo unnecessarily.

--
Simon Elliott http://www.ctsn.co.uk
Jul 22 '05 #9
"Michael" <sl***********@ hotmail.com> wrote in message news:<ck******* ***@hercules.bt internet.com>.. .
Ok Guys,
on the same thread
I'm writing a Game engine, which performs collision detection.
I want to sepate the collision boundings libaray from the main game engine
and load it as a library.
If simplified this example but it illustrates the point.... :-)

So i declare an abstract base class ( & function ): [...] class BoundingObject
{
public:
virtual int GetShape() =0;
}; BoundingObject* CreateBoundingO bject( vector<Triangle s>& tris);
bool GetCollision(Bo undingObject* b1,BoundingObje ct* b2); //Boundings.cpp
////////////////////////////////
#define B_SPHERE 1
#define B_BOX 2
#define B_TRIANGLE 3
[snip - derived for sphere, box, and triangle] bool IsCollisionSphe reSphere(Boundi ngSphere* s1,BoundingSphe re* s2);
bool IsCollisionSphe reBox(BoundingS phere* s1,BoundingBox* s2);
bool IsCollisionSphe reTriangle(Boun dingSphere* s1,BoundingTria ngle* s2); bool GetCollision(Bo undingObject* b1,BoundingObje ct* b2)
{
if( b1.GetShape() == B_SPHERE)
{
if( b1.GetShape() == B_SPHERE) return IsCollisionSphe reSphere(
static_cast<Bou ndingSphere*> b1,

static_cast<Bou ndingSphere*> b2 );

if( b2.GetShape() == B_BOX ) return
IsCollisionSphe reBox( static_cast<Bou ndingSphere*> b1,

static_cast<Bou ndingBox*> b2 );
//etc....
}
//etc

}


I belive this was covered in a DDJ article in the past year. The
solution used double dispatch. I'm sure you can find it online.
/david
Jul 22 '05 #10

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

Similar topics

9
4824
by: justanotherguy63 | last post by:
Hi, I am designing an application where to preserve the hierachy and for code substitability, I need to pass an array of derived class object in place of an array of base class object. Since I am using vector class(STL), the compiler does not allow me to do this. I do realize there is a pitfall in this approach(size of arrays not matching etc), but I wonder how to get around this problem. I have a class hierachy with abstract base...
7
2261
by: relient | last post by:
Question: Why can't you access a private inherited field from a base class in a derived class? I have a *theory* of how this works, of which, I'm not completely sure of but makes logical sense to me. So, I'm here for an answer (more of a confirmation), hopefully. First let me say that I know people keep saying; it doesn't work because the member "is a private". I believe there's more to it than just simply that... Theory: You inherit,...
4
5253
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:
0
2152
by: robert | last post by:
Hi all, I'm having a hard time resolving a namespace issue in my wsdl. Here's an element that explains my question, with the full wsdl below: <definitions name="MaragatoService" targetNamespace="http://swaMaragatoNS" xmlns:tns="http://swaMaragatoNS" xmlns="http://schemas.xmlsoap.org/wsdl/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
5
2627
by: Dennis Jones | last post by:
Hello, I have a couple of classes that look something like this: class RecordBase { }; class RecordDerived : public RecordBase {
19
2252
by: jan.loucka | last post by:
Hi, We're building a mapping application and inside we're using open source dll called MapServer. This dll uses object model that has quite a few classes. In our app we however need to little bit modify come of the classes so they match our purpose better - mostly add a few methods etc. Example: Open source lib has classes Map and Layer defined. The relationship between them is one to many. We created our own versions (inherited) of Map...
2
2420
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...
5
1498
by: alexl | last post by:
I have 2 classes, class base { public: some virtual functions } class derived : public base { public:
10
3616
by: Dom Jackson | last post by:
I have a program which crashes when: 1 - I use static_cast to turn a base type pointer into a pointer to a derived type 2 - I use this new pointer to call a function in an object of the derived type 3 - this function then 'grows' the derived type object (by pushing onto a vector).
0
10039
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
9883
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,...
0
11359
Oralloy
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...
1
11069
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
10543
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
9734
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
7259
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
6149
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4779
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

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.