Friday 23 December 2011

Koenig Lookup/ Argument -Dependent Lookup


Koenig Lookup/ Argument -Dependent Lookup


lets suppose the following scenario -->


//Trivial namespace for testing purpose
namespace test
{


class A { }; //Empty Class
void f(int x) {  cout<<x; } //simply ouputs the integer value passd
int f(A obj) { cout<<"OBJECT"; } //Prints OBJECT and takes an object of class A


}


int main()
{
//Inside main() i make a simple function call
f(10);
}


Now what will happen is that the compiler will search the global/free functions for 


similar signature, but wont find one because there aint one. The function 
void f(int x) is the namespace test and is inaccesible there until we use 
using namespace test;
Now if i add a function 


int f(int x)
{ cout<<x; }


int main()
{
//Inside main() i make a simple function call
f(10);
}


just before main() i.e in the global region, then the compiler will find a match when 


called through main(). This is all so simple and obvious, isnt it?
 Now a similar case -->


//Trivial namespace for testing purpose
namespace test
{


class A { }; //Empty Class
void f(int x) {  cout<<x; } //simply ouputs the integer value passd
int f(A obj) { cout<<"OBJECT"; } //Prints OBJECT and takes an object of class A


}


int f(test::A obj) { cout<<"ANOTHER OBJECT"; } //Similar to function inside namespace


//but this one is just in global scope


int main()
{
//Inside main() i make a simple function call
test::A obj;
f(obj);
}


Now what will happen in this case. the obvious answer would be that global f() would be 


called and ANOTHER OBJECT will be printed. but heres the truth guyz, the compiler will 


deflect slightly from usual name-lookup and will use another kind of name-lookup because 


the parameter you passed to the function is an object of a class/structure.
This kind of name-lookup is called KOENIG LOOKUP/ARGUMENT DEPENDENT LOOKUP.
and it would lead to an ambiguous call, the compiler would get confused between
test::f(A obj) and global int f(test::A obj)
although theres no using directive used.


The compiler will follow this rule --->


"If the parameter passed to a function is an object of a class/structure then the compiler 


would also include those namespaces in which that class/structure or its object is 


defined."


Well you would be thinking that whats the use of namespaces then, the namespaces are 


still functional and continue to serve their purpose, but this is just one rare case in which 


the compiler crosses the namespace boundary.
This kind of lookup called KOENIG LOOKUP was named after Andrew Koenig who nailed 


its proper definition.

Saturday 17 December 2011

Using pimpl idiom C++


The Infamous pimpl idiom C++

Pimpl standing for Private Implementation is a famous C++ idiom  particularly popularized in Herb Sutter's Guru of the week column (www.gotw.ca).
It describes a way for hiding your class's private members,by making them invisible from your Header file. Remeber this fact that whenever compiler sees your class, it only sees the header file (.h) and not the implementation file (.cpp). So what this basically does is that it removes all your private members from your header file(.h) and adds them to your implementation file (.cpp). Additional advantage of this technique is that it makes your class immune to changes meaning that you dont need to recompile it again and again if you change the private memebers. Also it keeps you public interface clean, and the client programmer doesn't need to be aware of you private members. It achieves this by using an opaque pointer, which is a pointer to a forward declared class or structure.

Eg:
struct B_impl; //Forward declared structure
class A {
B-impl *my_Impl; //Opaque pointer
}

Here Structure B-impl is only forward declared so the pointer my_Impl is an opaque pointer.
Now lets jump directly into action and see how pimpl is implemented :

This is our class :
//file A.h
//So many header files increases compile time :(
#include<A.h>
#include<B.h>
#include<C.h>
#include<D.h>
#include<vector>


class A
{
B objB;
C objC;
vector vlist<D>;
}

Now lets implement pimp idiom --->
//file A.h
//What happened to all the header files.....??
strcut pimpl; //forward declared structure 
class A
{
pimpl *my_impl; //opaque pointer to implement pimpl
}


//file A.cpp
#include<A.h>


strcut pimpl
{
B objB;
C objC;
vector vlist<D>;
}

So this is how we implement pimpl :
1. forward declare some structure/class
2. Make a pointer of that strcutrure/class known as opaque pointer
3. Declare all the private members in the .cpp file inside the structure/class.

Now the big question is that what should go inside the pimpl strcuture/class....??
Remember some basic points in mind while designing pimpl idiom.
---> Take all your non-virtual private members (variables + functions)
---> Never take protected members, because they were made protected at the first place so that the derived class can see them, if you hide them then whats the point of making them protected in the first place...??
---> Make your pimpl structure/class exactly as your class A would have been and make your class A just as a plain easy to use public interface with forwarding functions.

But finally the question arrives "was the pimpl implementation worth the pain..."??
the question will always depend on the programmer who is implementing it. For what class he is implemeting it.

Thursday 15 December 2011

How to reduce compile time dependencies


How to reduce compile time dependencies

The main culprit behind compile time dependencies is the huge amount of header files that are included by the compiler. Header files that are required in the code will obviously be added, but some programmers out of just habit include some useless header files as well. For eg :
In this code few header file will not be reqired

//Header files:
#include<iostream>
#include<ostream>
#nclude<B.h>
#nclude<C.h>
#nclude<A.h>


claas A {


B *obj;
C *obj;
 virtual std::ostream& print( std::ostream& ) const;


}

From the above code we can remove B.h and C.h straight away and use forward declaration instead of includeing those header files. Now what the hell is this FORWARD DECLARATION...??
Forward declaration is when we just declare and dont define.
Suppose we are just using references or pointers to B or C, then we can get away with forward declaration and dont need to include the header files.

  class B ; //Forward declaration only no need to include
  
  class A {
    private:
      B* fPtrB ;
    public:
      void mymethod(const& B) const ;
  } ;
But if we derive from B or C or uses objects of B or C, then we need to include their header files.

#include<B.h> //Header file included
  class A : public B{
  
  } ;
  
  class C {
    private:
      B objB ;
    public:
      void mymethod(B par) ;   
  }

Also we can remove #include<iostream> as well, dont be confused with the word stream, its not necessary that whenever you encounter the word stream you include <iostream>.
Here ostream is used and when can use #include<ostream> only and it will suffice.


So after clearing all the unwanted header files, heres what our code looks like :

//Header files:


#include<ostream>
#nclude<A.h>


claas A {


B *obj;
C *obj;
 virtual std::ostream& print( std::ostream& ) const;


}

One more thing we can do here is that we can use <iosfwd> instead of <ostream>,
what it will do is forward declare all the necessary things for ostream.

Some of you might also be wondering that whats the difference between function prototype and forward declaration.

In writing a function prototype you don't need to define parameter names, just their data type will suffice
int add( int, int );
but in forward declaration you need to specify their name as well,tough both will fulfill you requirements.

1 more thing that might interest you guys is that, think what will happen when you only declare the function and don't define it and then call it.........???

int add(int a, int b)

int main()
{
cout<<"Sum of 5 and 10 is "<<add(5,10);

return 0;
}

We have declared add but never defined it and also used it in our code...
So compiling will succeed but linking will fail and it will give error unresolved external symbol.

Sunday 4 December 2011

How to move something in games c++


Movement in game programming

I will be explaining you the basics of movement in 2D Games. Its a very simple concept which anyone can implement in their respective framework after understanding the basics.
Its done by repeatedly calculating new position from the previous coordinates. Its pure 2D vector maths, so u should be familiar with that also. So now here the is the formula known to Game programmers as
 "MOVEMENT FORMULA" :

New position = Old position + Speed * Direction

This is the basic formula which makes anything move in games.
If you want to move something in X direction, simply

sprite.x = sprite.x + sprite.speed * sprite.direction;

Similarly to move in Y direction :

sprite.y = sprite.y + sprite.speed * sprite.direction

For eg:
You have to move a bird from one side of the screen to other, in X axis only. So you set the starting coordinates to lets suppose (-10,0), set up its speed ,suppose 5 and direction 1 .
 Now lets apply this formula and move the bird.
bird.x = bird.x + bird.speed*bird.dir;
In the first frame:
-10 + 5*1 = 5
Next frame
-5 + 5*1 = 0
next frame
0 + 5*1 = 5;
and so on.....

So bird will first be rendered at (-10,0)
in the next frame (-5,0) then (0,0) then (5,0) and so on......this will give you an illusion of movement of the bird.
If you want to make it move in the opposite direction simply take direction as -1.

Now lets suppose you want to make it in a certain angle.
Simply move in both directions
Simultaneously change its X and Y co-ordinates.
Now lets get into VECTORS.








Like in this image you want to get to a specific point like you have to move from A --> B
Then A will have some cordinates and it will be a vector, similarly B will be another vector
So now we have co-ordinates,speed but we dont know the direction, for that
 B - A = C
Normalizing that vector C will give us the direction, which we can then use in our movement fformula.

The point to remember is that if A has to move to point B, then
B - A will be done, if B has to move to A,
then A - B will be done.
To make it even more useful and realistic you can include more variables like
FRICTION
ACCELERATION
GRAVITY,etc.

Try this thing by actually coding it up and get first hand experience. An explaination including actual code will follow soon.