Archive for August, 2007

Operator Overloading.The Big Questions.

Operator overloading is one feature with c++ which has been induced with no real object oriented philosophy to support. But its one feature every java guys crave for. Why? The answer is obvious. Better readability and ‘makes-sense’. Let me clarify this point.

Lets assume2 objects of class type Point which need to add the corresponding x & y coordinated and returns a Point object

Lets try implement this with an Add( )member function
class Point
{
   int x;
   int y;
Public:
 Point add(Point  P1,Point P2);
};

So when ever you want to add two points this is what you will be doing and it works fine.

Point Result = varPoint.Add(Point1,Point2);

Now lets see how the same can be achieved using overloading The ‘+’ operator using operator overloading

class Point
{
   int x;
   int y;
Public:
 Point operator+ (Point & a, Point & b);
};

So when you want to add two points all you have to do is

Point PointResult = Point1 + Point2;

Now its up to you to interpret which style looks “normal” !!

Talking about operator overloading it will be of interest to imagine about following scenarios 

  • Operator overloading functions as Friends
  • Making operator overloading functions global

Now it smells nonsense, But its not!
You dig into any frame work classes you will find plenty of the above two species of operator over loaders. Which follows the next big question…WHY?

Hidden overheads with empty Constructor/Destructor

Consider the following C++ code: 

        class A {
                int x, y, z;
        public:
                A();
        };

        class B {
                A a;
        public:
                B() {}
        };

        A::A() {x = 0; y = 0; z = 0;}

Class A has a constructor A::A(), used to initialize three of the class’s data members. Class B has a constructor declared inline (defined in the body of the class declaration). The constructor is empty.

Suppose that we use a lot of B class objects in a program. Each object must be constructed, but we know that the constructor function body is empty. So will there be a performance issue?

The answer is possibly “yes”, because the constructor body really is NOT empty, but contains a call to A::A() to construct the A object that is part of the B class. Direct constructor calls are not used in C++, but conceptually we could think of B’s constructor as containing this code: 

        B::B() {a.A::A();}      // construct “a” object in B class

There’s nothing wrong about doing things; it falls directly out of the language definition. But in complex cases, such as ones involving multiple levels of inheritance, a seemingly empty constructor or destructor can in fact contain a large amount of processing.


 

August 2007
S M T W T F S
« Jul   Sep »
 1234
567891011
12131415161718
19202122232425
262728293031  

Categories

Blog Stats

  • 29,660 hits

Last 100 Visitors

Map IP Address

Map IP Address