473,320 Members | 2,092 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

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 1657
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***********************@news.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.

Alternatively 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 "differently" 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* CreateBoundingObject( vector<Triangles>& tris);
bool GetCollision(BoundingObject* b1,BoundingObject* 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 BoundingTriangle : public BoundingObject
{
// specific data
virtual int GetShape() { return B_TRIANGLE; }
};

bool IsCollisionSphereSphere(BoundingSphere* s1,BoundingSphere* s2);
bool IsCollisionSphereBox(BoundingSphere* s1,BoundingBox* s2);
bool IsCollisionSphereTriangle(BoundingSphere* s1,BoundingTriangle* s2);
bool GetCollision(BoundingObject* b1,BoundingObject* b2)
{
if( b1.GetShape() == B_SPHERE)
{
if( b1.GetShape() == B_SPHERE) return IsCollisionSphereSphere(
static_cast<BoundingSphere*> b1,

static_cast<BoundingSphere*> b2 );

if( b2.GetShape() == B_BOX ) return
IsCollisionSphereBox( static_cast<BoundingSphere*> b1,

static_cast<BoundingBox*> 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->pBoundingObject = BoundingObject* CreateBoundingObject(
pObj->triData ) ;

object* pObj2 = new Obj;
// Some specific code.... //
pObj2->pBoundingObject = BoundingObject* CreateBoundingObject(
pObj->triData ) ;

bool IsCol = IsCollision(pObj1,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.********@comAcast.net> wrote in message
news:Tj****************@newsread1.dllstx09.us.to.v erio.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.btinternet.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* CreateBoundingObject( vector<Triangles>& tris);
bool GetCollision(BoundingObject* b1,BoundingObject* 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 BoundingTriangle : public BoundingObject
{
// specific data
virtual int GetShape() { return B_TRIANGLE; }
};

bool IsCollisionSphereSphere(BoundingSphere* s1,BoundingSphere* s2);
bool IsCollisionSphereBox(BoundingSphere* s1,BoundingBox* s2);
bool IsCollisionSphereTriangle(BoundingSphere* s1,BoundingTriangle* s2);
bool GetCollision(BoundingObject* b1,BoundingObject* b2)
{
if( b1.GetShape() == B_SPHERE)
{
if( b1.GetShape() == B_SPHERE) return IsCollisionSphereSphere(
static_cast<BoundingSphere*> b1,

static_cast<BoundingSphere*> b2 );

if( b2.GetShape() == B_BOX ) return
IsCollisionSphereBox( static_cast<BoundingSphere*> b1,

static_cast<BoundingBox*> 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->pBoundingObject = BoundingObject* CreateBoundingObject(
pObj->triData ) ;

object* pObj2 = new Obj;
// Some specific code.... //
pObj2->pBoundingObject = BoundingObject* CreateBoundingObject(
pObj->triData ) ;

bool IsCol = IsCollision(pObj1,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.********@comAcast.net> wrote in message
news:Tj****************@newsread1.dllstx09.us.to.v erio.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::Instance().CreateInstance(fooType);
}
DoStuffToFoo(int someArg)
{
foo_->DoStuff(someArg);
}
};

OK so far (so long as the user remembers to call bar::ChangeFoo()
before calling bar::DoStuffToFoo(); 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::DoStuffToFoo() 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.btinternet.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* CreateBoundingObject( vector<Triangles>& tris);
bool GetCollision(BoundingObject* b1,BoundingObject* b2); //Boundings.cpp
////////////////////////////////
#define B_SPHERE 1
#define B_BOX 2
#define B_TRIANGLE 3
[snip - derived for sphere, box, and triangle] bool IsCollisionSphereSphere(BoundingSphere* s1,BoundingSphere* s2);
bool IsCollisionSphereBox(BoundingSphere* s1,BoundingBox* s2);
bool IsCollisionSphereTriangle(BoundingSphere* s1,BoundingTriangle* s2); bool GetCollision(BoundingObject* b1,BoundingObject* b2)
{
if( b1.GetShape() == B_SPHERE)
{
if( b1.GetShape() == B_SPHERE) return IsCollisionSphereSphere(
static_cast<BoundingSphere*> b1,

static_cast<BoundingSphere*> b2 );

if( b2.GetShape() == B_BOX ) return
IsCollisionSphereBox( static_cast<BoundingSphere*> b1,

static_cast<BoundingBox*> 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
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...
7
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...
4
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...
0
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"...
5
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
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...
2
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...
5
by: alexl | last post by:
I have 2 classes, class base { public: some virtual functions } class derived : public base { public:
10
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...
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
0
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
0
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....

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.