Tuesday, June 19, 2007

Minimize casting

rules of c++ are designed to guarantee that type errors are impossible.

casting is more necessary and less dangerous in c and java than c++. approach it carefully in c++

old style casts: (T) expression , T(expression) ---both are exactly same

are these really same....i think second one invokes the defined conversion operator ...whereas first one just causes reinterpretation????

newer casts
const_cast( expression)
dynamic_cast(expression)
reinterpret_cast(expression)
static_Cast(expression)

dynamic cast may have a significant runtime cost
reinterpret_cast means trouble, low level use only, results in unportable code

i dont understand why this should work ? ???
class widget {
public:
explicit widget(int size);
};
dosomework( static_cast(15));

how does this work with that constructor is explicit ???

derived d ;
base* bp = &d;
bp and &d maynt be same ...in both single inheritance and virtual inheritance
this cant happen in c and java and c#.

can operators be virtual functions?

class window {
public:
virtual void onResize() { ...}
};
class specialwindow:public window {
public:
virtual void onResize(){
static_cast(*this).onResize();
}
};
onresize doesnt call onresize on the base object. it makes a copy of the base object part and calls it on that object. use window::onResize for the effect.

cast creates a new temporary copy of the base class part.

if you find urself wanting to case its a sign that you could be approaching things the wrong way.

dynamic cast:
it can be quite slow.
one common implementation is based in part on string comparison of class names
s oa single 4 level hierarchy means upto 4 comparisons for each cast.

deeper or multiple inheritance hierarchies are more costly....its implemented this way to support dynamic linking
be afraid of dynamic cast in performance sensitive code.

you can maybe define a virtual function to avoid casts or have only single type of objects in a container to avoid it.

things to remember:
avoid casrs whenever practical, esp dynamic casts in performance sensitive code. if a design requires casting, try to develop a cast free alternative.

when casting is necessary try to hide it inside a function. clients can then call the function instead of putting casts in their own code

prefer c++ style casts to old style casts. they are easier to see and they are more specific about what they do.

No comments: