473,231 Members | 1,394 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,231 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 1653
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: VivesProcSPL | last post by:
Obviously, one of the original purposes of SQL is to make data query processing easy. The language uses many English-like terms and syntax in an effort to make it easy to learn, particularly for...
3
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 3 Jan 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). For other local times, please check World Time Buddy In...
0
by: abbasky | last post by:
### Vandf component communication method one: data sharing ​ Vandf components can achieve data exchange through data sharing, state sharing, events, and other methods. Vandf's data exchange method...
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 7 Feb 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:30 (7.30PM). In this month's session, the creator of the excellent VBE...
0
by: fareedcanada | last post by:
Hello I am trying to split number on their count. suppose i have 121314151617 (12cnt) then number should be split like 12,13,14,15,16,17 and if 11314151617 (11cnt) then should be split like...
0
by: stefan129 | last post by:
Hey forum members, I'm exploring options for SSL certificates for multiple domains. Has anyone had experience with multi-domain SSL certificates? Any recommendations on reliable providers or specific...
1
by: davi5007 | last post by:
Hi, Basically, I am trying to automate a field named TraceabilityNo into a web page from an access form. I've got the serial held in the variable strSearchString. How can I get this into the...
0
by: MeoLessi9 | last post by:
I have VirtualBox installed on Windows 11 and now I would like to install Kali on a virtual machine. However, on the official website, I see two options: "Installer images" and "Virtual machines"....
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...

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.