Tuesday, January 24, 2012

Argument Resolution virtual Function

Consider the following program:


#include "stdio.h"
enum ShapeColor { Red, Green, Blue };
class Shape
{
public:
    virtual void draw(ShapeColor color=Red) const = 0;
    void PrintColor(ShapeColor c) const {
        switch(c) {
        case Red:   printf("Red\n");
            break;
        case Green: printf("Green\n");
            break;
        default:  printf("Blue\n");
       }
    }
};
class Rectangle : public Shape {
public:
    void draw(ShapeColor color=Green) const
    {
        printf("From Rectangle\n");
        PrintColor(color);
    }
};
class Circle : public Shape {
public:
    void draw(ShapeColor color=Green)  const {
        printf("From Circle\n");
        PrintColor(color);
    }
};
int main() {
   Rectangle r;
   Shape *ps = &r;
   ps->draw();
   Circle c;
   ps = &c;
   ps->draw();
   return 0;
}

Output of above code is as below:
From Rectangle
Red
From Circle
Red
 
From the output of above program it is clear that for virtual function, actual 
function called is resolved at runtime but the default value of the argument is 
get resolved in compilation time.
 



Now this time I leave this on you to analysis and comment on this program its output and default value resolution of virtual function at compile time as well as on run-time.

Waiting for you comment.





Saturday, January 21, 2012

C++ Multiple Inheritance and Class size

While learning or developing any C++ application you must have used the Multiple-inheritance feature provided by language. Lot has been written about it in many places how it do it, how it works and what is what  in multiple inheritance.
There is a very basic thing with respect to multiple inheritance what will be the size of object ?
Consider following hierarchy.
#include<iostream>
using namespace std;
class Base {
     public:
           int a;
};
class X:public Base {
     public:
           int x;
};
class Y:public Base {
     public:
           int y;
};
class Z:public X,public Y
{ };
int main(){
    Z z;
    cout <<"size of z = "<< sizeof(z) <<endl;
return 0;
}
Definitely the output will be 16 considering 32 bit int.
Class Name
Size in Bytes(32 bit integer)
Base
4 ( sizeof(a) )
X
8 ( sizeof(x) + sizeof(Base) )
Y
8 ( sizeof(y) + sizeof(Base) )
Z
16 ( sizeof(X) + sizeof(Y) )
 
In virtual base class there will be only single object and all the classes which derives 
virtual base class requires a pointer to it so that they can access it. 
Consider following hierarchy using virtual inheritance as follow:
#include <iostream>
using namespace std;
class A {
    int a;
};
class B   : public virtual A {
    int b;
} ;
class C : public virtual A {
    int c;
};
class D : public virtual B, public virtual C {
    int d;
};
class E : public B, public C {
    int e;
};
class F : public B, public C{};
class G : public virtual B, public virtual C {};
int main() {
    A a;
    B b;
    C c;
    D d;
    E e;
    F f;
    G g;
    cout << " size of A" << sizeof(A) << endl;
    cout << " size of B" << sizeof(B) << endl;
    cout << " size of C" << sizeof(C) << endl;
    cout << " size of D" << sizeof(D) << endl;
    cout << " size of E" << sizeof(E) << endl;
    cout << " size of F" << sizeof(F) << endl;
    cout << " size of G" << sizeof(G) << endl;
    return 0;
}

Output:
 size of A4
 size of B12
 size of C12
 size of D28
 size of E24
 size of F20
 size of G24
 
Memory Layout:
(gdb) display a
1: a = {a = -6800}
(gdb) display b
2: b = {<A> = {a = 0}, _vptr.B = 0x401188, b = 4196304}
(gdb) display c
3: c = {<A> = {a = 0}, _vptr.C = 0x401168, c = 4197632}
(gdb) display d
4: d = {<B> = {<A> = {a = 0}, 
               _vptr.B = 0x4010c0, b = 6296960}, 
        <C> = {_vptr.C = 0x4010d8, c = 608253861},
        _vptr.D = 0x4010a8, d = 0}
(gdb) display e
5: e = {<B> = {<A> = {a = 6298088}, 
                      _vptr.B = 0x400ff8, b = 6}, 
        <C> = {_vptr.C = 0x401010, c = 4196224}, 
        e = 0}
(gdb) display f
6: f = {<B> = {<A> = {a = 0}, 
               _vptr.B = 0x400f58, b = 4196998}, 
        <C> = {_vptr.C = 0x400f70, c = 4197725}, 
        <No data fields>}
(gdb) display g
7: g = {<B> = {<A> = {a = 0}, 
               _vptr.B = 0x400ea0, b = 6296960},
        <C> = {_vptr.C = 0x400eb8, c = 1}, 
        _vptr.G = 0x400e88}
 
Here is a memory size table for individual class:
 
Class Name
Size in Bytes(32 bit integer) 
A
4 ( sizeof(A) )
B
12 (sizeof(A *) + sizeof(vptr.B) + sizeof(int))
C
12 (sizeof(A *) + sizeof(vptr.C) + sizeof(int))
D
28 (sizeof(A *) + (sizeof(B *) + sizeof(vptr.B)   + sizeof(C *) + sizeof(vptr.C)+ sizeof(vptr.D) + sizeof(int))
E
24 (sizeof(A *) + (sizeof(B *) + sizeof(vptr.B)   + sizeof(C *) + sizeof(vptr.C) + sizeof(int))
F
20 (sizeof(A *) + (sizeof(B *) + sizeof(vptr.B)   + sizeof(C *) + sizeof(vptr.C))
G
28 (sizeof(A *) + (sizeof(B *) + sizeof(vptr.B)   + sizeof(C *) + sizeof(vptr.C)+ sizeof(vptr.D))

Above table explains how the size is calculated in Multiple inheritance. 
*** In some compiler size may vary due to padding done by compiler for memory alignment.

Thursday, January 19, 2012

Explicit Constructor C++

The C++ is designed in such a way that by default,a single argument constructor also defines an implicit conversion. In C++, an implicit conversion is a conversion from one type to another that doesn't require an explicit typecast. For example consider following class:

class Conversion {
public:
    Conversion(int o=0) : data(o) {    }
    int getData() { return data;}
private:
    int data;
};

int main(){
  Conversion c = 5;   // initialize c with Conversion(5)
  cout << c.getData() << endl;
  return 0;
}


Here the constructor worked as implicit converter. 
But there are cases where this feature can play bad. Consider following: 
 
class MyString {
public:
    MyString(const char* str);        // initial val is c-style string  str 
    MyString(const int len=0);        // pre-allocate len bytes
    const char* getData() const { return c;}
private:
    char *c;
    unsigned int len;
};
MyString::MyString(const int len) {
   this->len=len;
    c= new char[len+1];
}
MyString::MyString(const char *str) {
    len = strlen(str);
    c = new char[len+1];
    strcpy(c, str);
}
int main()
{
  MyString m_str = "it works here"; //MyString(const char *str)
  cout << m_str.getData()<< endl;
  MyString m_str2 = 'a';            //MyString(const int len)
  cout << m_str2.getData() << endl;
  return 0;
} 

Now, MyString m_str2 = 'a'; makes m_str2 a string with 'a' char, its quite unlikely 
that this is what person want. So make sure that the conversion is intuitive and
consistent with major C++ conventions. If not, consider using non-constructor member functions.

To prevent above discussed problem C++ comes up with explicit keyword, that suppressed the implicit conversion. That is, an explicit constructor will be invoked only explicitly. So if we modify above class declaration as follow:

class MyString {
public:
    MyString(const char* str);        // initial val is c-style string  str 
    explicit MyString(const int len=0);        // pre-allocate len bytes
    const char* getData() const { return c;}
private:
    char *c;
    unsigned int len;
};

Now for line
    MyString m_str2 = 'a';    

We will get compiler error since there's no implicit conversion from char to int. How ever we can still write
    MyString m_str2(10); 
Which is what we were trying to accomplish in the first place.
 
When designing classes, if you have a single-argument constructor that is not intended
 as a conversion function, you must mark it explicit to avoid running into the “implicit conversion” trap. 






Monday, January 16, 2012

STL List remove()

STL Lists are a kind of sequence container and among the most widely used. 
Here i will discuss just about one function remove.
void remove(const T& value)
SGI says: Removes all elements that compare equal to val. The relative order of elements that are not removed is unchanged, and iterators to elements that are not removed remain valid. This function is linear time: it performs exactly size() comparisons for equality.
    So if we have a list of integer say:           lst: 1,2, 4,6 4,5,9
    and we say                                            lst.remove(4);
    then remaining list be                              lst: 1,2,6,5,9
Internally remove function iterate complete list, compare and remove all elements equal to 4.  With intrinsic /in-built data-type simple comparison provided by c++ works fine.
Now what if we have a list of  class object. 
As in following example:

#include "iostream"
#include "list"
using namespace std;
class lstTest {
public:
    lstTest(int d=0):i(d) {}
    int getData() const {return i;} 
private:
    int i;
};
int main() {
    list lstObj;
    list::iterator itr;
    lstTest t(10);
    lstObj.push_back(lstTest(11));
    lstObj.push_back(lstTest(2));
    lstObj.push_back(t);
    lstObj.push_back(lstTest(11));
    for(itr=lstObj.begin(); itr!= lstObj.end();itr++)
        cout << (*itr).getData() << endl;
    lstObj.remove(t);
    for(itr=lstObj.begin(); itr!= lstObj.end();itr++)
        cout << (*itr).getData() << endl;
    return 0;
}
on compilation we get following error:

/usr/lib/gcc/x86_64-redhat-linux/4.6.1/../../../../include/c++/4.6.1/bits/list.tcc: In member function ‘void std::list<_Tp, _Alloc>::remove(const value_type&) [with _Tp = lstTest, _Alloc = std::allocator, std::list<_Tp, _Alloc>::value_type = lstTest]’:
listTest.cpp:25:20:   instantiated from here
/usr/lib/gcc/x86_64-redhat-linux/4.6.1/../../../../include/c++/4.6.1/bits/list.tcc:249:4: error: no match for ‘operator==’ in ‘__first.std::_List_iterator<_Tp>::operator* [with _Tp = lstTest, std::_List_iterator<_Tp>::reference = lstTest&]() == __value’
/usr/lib/gcc/x86_64-redhat-linux/4.6.1/../../../../include/c++/4.6.1/bits/list.tcc:249:4: note: candidates are:
/usr/lib/gcc/x86_64-redhat-linux/4.6.1/../../../../include/c++/4.6.1/bits/postypes.h:218:5: note: template bool std::operator==(const std::fpos<_StateT>&, const std::fpos<_StateT>&)
...
...

so why this Kolavery..... Kolavery ji...

As i discussed earlier remove perform comparisons for equality so for UDT we need to help remove(...) by providing customize "==" operator for class in question. 
For this we need to implement bool operator ==(...) function for class.
So we add following function to  above class:

class lstTest {
public:
    lstTest(int d=0):i(d) {}
    int getData() const {return i;}
    friend bool operator==(const lstTest& o1, const lstTest& o2);
private:
    int i;
};
bool operator==(const lstTest& o1, const lstTest& o2) {
        return o1.i== o2.i;
}

After this "==" overloading above code will works fine.

Now what if you want some thing like this with same class:
    lstObj.remove(11); // removing all object with value of i  = 11
For this we again need to implement another "==" operator for class as follow:
function declaration in class:
friend bool operator==(const lstTest& o1, const int& i);
function definition:
bool operator==(const lstTest& o1, const int& i) { return o1.i== i;}







Sunday, January 15, 2012

Singleton Pattern


Design Pattern's a tool to avoid resolving the already solved problem. Just apply the existing solution and your problem is solved. Patterns don't go directly into code, they first go into your mind. Once you train it with working knowledge, you then apply them to your design for any given problem or your old problem.

When ever design pattern comes to you first pattern that come into mind is Singleton. The singleton pattern deals with situations where only one instance of a class must be created.

Definitions:
  1. Ensure only one instance, and provide a global point of access to it.
  2. Restrict a class so that only one instance can be created.
Features:
  • A single instance of a subsystem shall be enforced, and the subsystem itself shall be responsible for that enforcement.
  • The single instance shall be globally accessible.
  • The single instance shall be initialized only if, and when, it is accessed.

We can implement singleton class by doing following changes to any class:
  • Make following private
    • Constructor : to control instantiating 
    • Copy Constructor : do  not want to create copies.
    • Assignment Operator 
  • Create method that , creates a new instance of the class if one does not exist, return object reference.
Usages:
  • Base for implementing many other pattern like factory, abstract factory etc.
  • Very common use is to create logger for you application.
Problems:
  • Make debugging difficult 
  • extra care should be taken while implementing for threaded application.
Example:
/*                   Singleton.h                              */
#ifndef SINGLETON_H_
#define SINGLETON_H_

#define SINGLETON singleton::Singleton::getInstance()
namespace singleton {

class Singleton {
public:
 virtual ~Singleton();
 static const Singleton& getInstance();
        void doTask() const;

private:
 Singleton();
 Singleton(const Singleton &);
 Singleton& operator = (const Singleton &);
};

} /* namespace singleton */
#endif /* SINGLETON_H_ */


/*                   Singleton.cpp                              */
#include "Singleton.h"
#include "assert.h"
namespace singleton {

    Singleton::~Singleton() {
            // TODO  class cleaning
    }
    Singleton::Singleton() {
            // TODO  constructor stub
    }

    Singleton::Singleton(const Singleton & ref) {
            // TODO copy constructor    
    }
    // global interface

    const Singleton & Singleton::getInstance() {
        static Singleton obj;
        return obj;

    }
   

    Singleton & Singleton::operator =(const Singleton & ref) {
     assert(false);
     return *this;
    }
    // task performed by class
    void Singleton::doTask() const {
        cout << "task to do" << endl;
    }
}/* namespace singleton */

/*                   main.cpp                              */
#include "Singleton.h"
int main(int argc, char *argv[])  {
    SINGLETON.doTask();
    return 0;
}
/****************************************************************/