Search This Blog

Sunday, September 12, 2010

Wanna learn Design patterns?

If you are OOP guy with more than 3-4 years experience then mostly your interview wont complete without questions on "Design patterns".
Even if you don't want to prepare for interview you will need Design patterns knowledge to understand vocab in design discussions.
Even if you don't do job anywhere (which solves this vocab problem - I design software for my own!), Design patterns can be useful tools for saving your efforts in reinventing the wheel.

The most reliable and respected book on this subject by GoF (Gang of Four) Design Patterns : Elements of Reusable Object Oriented Software is difficult to understand (at least for beginners).

Thanks to Anwar Khan, my senior colleague who suggested me Head First Design Patterns (HFDP).  I thought that this book is for Java guys (you know I am C++ dude). But when Anwar convinced me that C++ and Jave both are OOP languages and if I understand C++ then I should be easily able to learn it from HFDP.
This book is great! Thanks a ton to authors for making subject easy to understand (they have also made learning fun :) ). The book teaches you patterns in such a great way that they permanently fit into your memory. Trust me you don't need Java background, but probably some OOP background is a must. This book explains most of the fundamental and commonly used design patterns in detail. It does not explain few patterns like Builder, Chain of responsibility and few others in detail. It does provide some Bird's Duck's eye view of these patterns. I am sure you will also like learning Design patterns from this book.

After you have read this book do not forget to read GoF's book. HFDP also guides you on how to make use of GoF's book. GoF's book is (according to me) ultimate book on this subject. I have not read GoF completely yet - but I am planning to do that soon.

Here are few web links (some I got from HFDP and some from Google), which are useful in learning design patterns -
http://c2.com/cgi/wiki?DesignPatterns
http://sourcemaking.com/design_patterns
http://www.vincehuston.org/dp/

In my own opinion if you are serious about OOP, then you should also read Grady Booch's Object Oriented Analysis and Design

If you have any useful links/ suggestion for book on this subject - please post a comment.

Tuesday, July 13, 2010

Is it necessary to specify virtual keyword in derived classes? (C++)

No - not at all necessary! BUT please do it so that the maintenance programmer wont have horror experience debugging your code :)

Let me support it with sample code :


#include <iostream>

using namespace std;

class Base {
public:
 Base() { cout << "Base::Base()" << endl; }
 virtual void VirtFun() { cout << "Base::VirtFun()" << endl; }
 virtual ~Base() { cout << "Base::~Base()" << endl; }
};

class Derived : public Base {
public:
 Derived() { cout << "Derived::Derived()" << endl; }
 void VirtFun() { cout << "Derived::VirtFun()" << endl; }
 ~Derived() { cout << "Derived::~Derived()" << endl; }
};

int main () {
 
 Base* pBase = new Derived();
 pBase->VirtFun();
 delete pBase;

 return 0;
}

Output of this program is :
Base::Base()
Derived::Derived()
Derived::VirtFun()          
Derived::~Derived()
Base::~Base()

Even though the virtual keyword is not specified in the Derived class - the VirtFunc() and Destructor of virtual class are automatically virtual (because virtual keyword is specified for them in Base class).

Also note that : only the functions which are specified as virtual in Base class will be by default virtual in the Derived classes. If the function is not virtual in Base class - then it is not so.

I am not sure whether this features is compiler dependent or not, I have tested this code using 'Microsoft Visual C++ 2005' and G++, both give same output.

Constructor Destructor and Virtual Keyword (C++)

One of the favorite interview question is -
Why destructor should be always virtual and constructor should never be virtual?

Let's discuss these 2 questions separately.

Before we start keep this class hierarchy in mind -

                                 Base
                                   ^
                                    |
        -------------------------------------------
       |                            |                             |
Derived1               Derived2                Derived3



1. Why is constructor never virtual?
While creating any object programmer always 'knows' which object he is creating i.e. Which class we want to instantiate.
e.g. Base *pBase = new Derived3();  // Though the pointer is of Base class type the programmer very
                                                         // well knows to write new Derived3()

In addition, also note that though virtual table in not specific to class instance (object), to call virtual function of any class first we need valid object of that class.
i.e. Virtual function can not be called unless we have constructed the object.

2. Why is destructor be always virtual?
There might be function of the type
void do_something_and_then_delete(Base *pBase) {
     // Do something with pBase

     delete pBase;
}

Now it is easy to understand that user might write some code like -
Base* pBase = new Derived1();
do_something_and_then_delete(pBase);
Base* pBase = new Derived2();
do_something_and_then_delete(pBase);
Base* pBase = new Derived3();
do_something_and_then_delete(pBase);

In all 3 cases correct destructor needs to get called.
User always knew name of the class to instantiate, but while deleting user did not have idea about which is the exact destructor he wants to call.
If the destructors of Derived classes are not virtual then the destructor of Base class will get called and it will lead to memory leaks and might be some other problems in the system.

If you have any better answer to improve this post please comment, I will modify the post.

Monday, June 14, 2010

Want to download website?

The best solution is to use wget.
For information regarding how to use? see -
http://en.wikipedia.org/wiki/Wget
If wikipedia is not sufficient use - man wget.

I have used this on Linux and on Cygwin (on windows).

wget is also available directly on windows -
1. Setup is available here -
http://gnuwin32.sourceforge.net/packages/wget.htm

2. wget is avaible with GUI for windows -
http://sites.google.com/site/jackparke/wgetgui
or
http://sourceforge.net/projects/wget-gui-kiwi/

Tuesday, May 25, 2010

C++ is multi paradigm programming language

I might have read this sentence at least 10-15 times in different C++ books, but did not understand (and appreciate) at those times, what it means :(.

This link might help you - Programming paradigm

In my experience typical (big) software product written in C++ uses C++ in different way (techie word : uses different programming paradigms). The application side part is moreover in OOP and the core algorithm side part is moreover functional (both coded in C++ :)).

I wont write much on this subject (as I do not understand this subject well), but once you start looking at your C++ code taking into account programming paradigms used at different levels, you will feel more proud being a C++ developer :).

I got following comment from Yogeshwar Shukla on Buzz. Adding it to original post (with little modifications)  -
References to some books
i) Chapter 2. The C++ Programming Language. - Bjarne Stroustrup (very terse)
ii) Part I and II of Object Oriented Software Construction by Bertrand Meyer (very elaborate). This not really introduce you to the meaning of paradigm but explains OO paradigm.
iii) The best discussion is in -
Concepts, Models and Techniques in Programming. It has a formal specification of programming paradigm and the entire book is devoted to discussion of paradigms in computer science known as yet


I will try to add few more good links, in future.

Tuesday, May 4, 2010

Changing visibility of member function in derived class

Few days back we had discussion in my company regarding "Whether square class should derive from Rectangle class or not?" (Please note this discussion was just part of debate and has nothing to do with source of software I work on)

You can google above question - you will get good amount of papers :). Here is one link

We were talking about the problem that having SetHeight() and SetWidth() methods in square's public interface does not look good.
I though of making these methods private. This looked perfect solution for me (*correction - poor me) for the problem in hand -


=========**=========**=========Code=========**=========**=========
 

#include <iostream>

using namespace std;

class Rectangle {
public:
 Rectangle() {mWidth = 0.0; mHeight = 0.0; }
 virtual void SetHeight (double Height);  // Access specifier is public 
 virtual void SetWidth (double Width);    // Access specifier is public 
 ~Rectangle() {}
protected:
 double mWidth;
 double mHeight;
};

void Rectangle::SetHeight(double Height) {
 mHeight = Height;
}

void Rectangle::SetWidth(double Width) {
 mWidth = Width;
}

class Square : public Rectangle {
public:
 Square() {mWidth = 0.0; mHeight = 0.0; }
 void SetDimension(double Dimension);
 ~Square() {}
private:
 virtual void SetHeight (double Height);   // Access specifier is private 
 virtual void SetWidth (double Width);     // Access specifier is private 
};

void Square::SetDimension(double Dimension) {
 mWidth = mHeight = Dimension;
}

void Square::SetHeight(double Height) {
 mWidth = mHeight = Height;
}

void Square::SetWidth(double Width) {
 mWidth = mHeight = Width;
}

int main () {
 Square mySquare;

 // mySquare.SetWidth(20.0);   // Compilation error - for calling private member
 Rectangle &rect = mySquare;
 rect.SetWidth(20.0);          // SetWidth() is public in Rectangle class :)

 return 0;
}
=========**=========**=========Code=========**=========**=========

As you can see in above code -
1. As expected user can not call SetWidth() on Square object directly.
2. But user can call SetWidth() on Square object indirectly using reference or Pointer
3. As shown in code rect.SetWidth(20.0) calls private function of Square!!
Because - SetWidth() is declared public (and importantly virtual) in Rectangle :), and since rect is reference to Square - call to rect.SetWidth() comes as a call to Square's private method because of C++'s virtual function mechanism!!

Don't forget C++ is tricky!

Note : the code I have discussed in this example is just for sake of example. Personally I would not have written such kind of code (at least) for any professional software.

Chaning const reference to pointer

Recently me and Chetan were puzzled, when we saw some code similar to -


=========**=========**=========Code=========**=========**=========



#include<iostream>

using namespace std;

class ABC {
public:
 ABC() {m_val = 0;}
 void change_state() {m_val ++;}
 ~ABC() {}
private:
 int m_val;
};


void function(const ABC *& p_abc) {
        // p_abc->change_state();     // Not Allowed
        p_abc = NULL;                 // Allowed
}

int main() {

 const ABC* p_abc = new ABC();  // p_abc is not const pointer!!

 // p_abc->change_state();      // Not Allowed
 function(p_abc);

 return 0;
}


=========**=========**=======Code End=======**=========**=========

We could not believe this (majic!!)
We thought this is wrong because p_abc is a const pointer!! - what do you say ;)
We even thought that there is some special compiler option!! which is allowing this to happen :)


The answer is, there is only one way to declare a const pointer is
Let's take example of constant pointer to integer -

int *const cnstPtr = new int();
The other two
const int * cnstObj1 = new int(); // and
int const * cnstObj2 = new int();
are declarations for pointer pointing to constant object! and the pointer itself is not constant!

Once again -
*cnstPtr = 5;       // OK - Object is not constant
cnstPtr = NULL;     // NOT OK - Pointer is constant

*cnstObj1 = 5;      // NOT OK - Object is constant
cnstObj1 = NULL;    // OK - Pointer is not constant
also
*cnstObj2 = 5;      // NOT OK - Object is constant
cnstObj2 = NULL;    // OK - Pointer is not constant

What if you want pointer and object both constant?
Use -

const int *const cnstPtrCnstObj1 = new int(); // or 
int const*const cnstPtrCnstObj2 = new int(); 

In this case -
*cnstPtrCnstObj1 = 5;     // NOT OK - Object is constant
cnstPtrCnstObj1 = NULL    // NOT OK - Pointer is constant

and
*cnstPtrCnstObj2 = 5;     // NOT OK - Object is constant
cnstPtrCnstObj2 = NULL    // NOT OK - Pointer is constant

Thanks to Chetan for showing the problem and then telling the cause :)

Saturday, April 24, 2010

Two wheeler (aka bike) : initial care

I bought Royal Enfield Thunderbird last Thursday. This bike is amazing!

I am doing some research on initial care of bike. You can use this information on your own risk, I do not have anything much to support my conclusions than commonsense and my BE (Mechanical) qualification.

Why do you need to take special care in initial months?
The same reason why baby needs special care in initial months :)
Engine which is heart of your bike is created using casting procedure and it is machined afterwards on CNC machines. It is highly possible that the surface finish of many parts inside the engine is not very smooth initially. When you start using engine, these parts get rubbed against each other. It is possible at this stage - if you have some small burs (small metal chips) remaining in the crankcase then these parts will get scratches. These initial scratches can result in big loss of efficiency and total engine life.

What are the general precautions one should take in initial months?
1. Give you bike some time to warm up!
Do not expect your bike ready for riding as soon as you start it. Think of it like someone has awakened you from sleep and now is forcing you for some heavy work.
When engine starts it takes some time for oil film layer to get developed between different friction-generating parts. If you give some time to your bike's engine to run on idling - this oil film will be developed before you actually go for ride.
2. Do not exceed speed (rpm) limits
Again as you know baby learns walking step by step and then after some time baby is able to run.
Similarly your vehicle first needs to be run on lower speeds, after each servicing max speed limit will be little higher. If you are lucky enough to have rpm meter then better keep eye on engine rpm than speed.
Reasons for initial speed limits are - same as the reasons explained in 'Why do you need to take special care in initial months?'
3. Try to ride on less crowded roads in initial days
Reason is simple - your engine will be running on almost constant rpm and also transmission system wont face much shocks.
4. Do not compromise on fuel and engine oil quality!
Using bad quality fuel/engine oil for bike is like eating bad quality food.
Remember - fuel is something which burns inside the engine cylinder, if it is of bad quality it is surely going to have bad effect on engine.
Engine oil does cleaning work inside engine and it is also responsible for maintaining temperature of engine unit. Engine oil is also responsible for reducing friction between the rubbing parts inside the engine.
5. If you get any vibration - noize or any other problem - get it repaired immediately.
Do not wait for servicing time to get these problems repaired. Ignoring these problem will result in making them bigger and making long life impact on your vehicle.
6. Avoid over-heating
Some people might think it is great to go for long rides in first few km. I think it is really good to go for long  rides in initial running, long runs do provide good conditions for engine and transmission system.
On highways engine rpm (speed) is almost constant and also gears are rarely shifted.
But do not forget that you should take enough breaks for engine to cool down. Over-heating might cause some problems (my gut feeling).

I will keep updating this post. If there are any mistakes in this post - please post comment. Your comments and suggestions are very much welcome.

Thanks to Harshad Sharma who helped me to think on these points.

Thursday, March 18, 2010

Some good websites for learning C++

Hello friends,

I love C++. I am learning it for past 4 years and till date I am not sure how much I know about it.

I am sharing here some of the sites which I find useful -
1. http://www2.research.att.com/~bs/bs_faq2.html - This is link for Bjarne Stroustrup's technical FAQ page. Learning C++ from Stroustrup is like learning creation of universe from God!. Whenever I come across difference of opinion with any other developer or friend - I use this site as first reference.

2. http://www.parashift.com/c++-faq-lite  - This site is like online C++ book, has got tremendous amount of information.

3. http://mindview.net/Books/TICPP/ThinkingInCPP2e.html - I think "Thinking in C++" is the nicest book to start learning C++. Thanks a ton to author Bruce Eckel for giving online copies of the boo

4. http://www.cplusplus.com/doc/tutorial - This is good site if you want code examples.

5. http://www.codeguru.com/cpp - Another good site for forums and examples.

I will update this post when I get new information.

Some good sites for learning photography

Hi friends,

I am learning photography for some time (learning => learning on my own => just for fun). I would like to share here some good sites.

Please do start with How Camera Works!! - This is excellent information. Very nicely explained.

Some other good sites -
1. http://photo.tutsplus.com/  (Main site for How Camera Works)
2. http://www.geofflawrence.com/
3. http://www.cambridgeincolour.com/tutorials.htm
4. http://niels-henriksen.blogspot.com/
5. http://www.dpreview.com/ (For reviews of different cameras)
6. http://www.jjmehta.com/ (You will get here best prices in India - Note : I do not have any personal interest in suggesting this shop)

I will keep updating sites in this post as I get to know about the better ones!.

Sunday, March 14, 2010

Books for developers working on Microsoft Windows

Hello friends,

I am writing here list of books which are good for developers working on windows based projects. I have not read all of those. I will put * for the books which I have read (fully or partially). Will try to write little about the books. Hope this post will be useful to windows application developers.

Windows application programming -
Advanced windows by Jeffrey Richter - must read!. Whether you do application programming or any other programming on windows this book is must read. Jeffrey Richter has made the complicated subject quite easy to understand. The books has got lots or examples. Chapters and source examples are chosen so nicely that if you already have some background in windows application programming you can skip some chapters and directly read the chapter of your interest. I should mention that "Advanced windows" is covers Microsoft windows 95 and NT 4.0.
Probably out of the list of books I have mentioned in this post this is the only book I have read from start to end, also tried all of the examples given in this book. 
If you want latest version then read -
Programming applications for microsoft windows - by Jeffrey Richter. Covers Microsoft windows 2000 and windows 98.
Windows via C/C++ - by Jeffrey Richter. Covers Vista.

Programming Windows - by Charles Petzold. Again a must have book. I think very few people will read it from start to end. This can be used as a reference book for windows GUI programming. Language is good (sometimes boring), again this book has lot of examples and source is available on Charles Petzold's web page for download.
I am currently reading old version of this book -
* Programming windows 95 and * Programming windows 3.1


Windows Internals related books -
* Inside windows 2000 - by David Soloman and Mark Russinovich.
Will give you lot of insight of Microsoft windows operating system. I am trying to read this (controlling my sleep :)). I think you will need to read this if you want to do things like device driver programming for Microsoft Windows.
Microsoft Windows Internals 4th edition -  by David Soloman and Mark Russinovich. Covers XP. Unfortunately I am not getting hard copy of this book :(.
Microsoft Windows Internals 5th edition - by David Soloman and Mark Russinovich. Covers Vista.


For COM (Component Object Model) and OLE (Object Linking and Embedding) -
* Understanding ActiveX and OLE - bye David Chappel. Hats off to David Chappel for making very very complicated subject understandable. His writing style is very good (This books has foreword from Kraig Brockschmidt). If you do not have any background for COM and want to start COM - do not read any book other than this one.

* Inside COM - by Dale Rogerson. Many people like this book to start learning COM, I am not exception. Language is quite simple - this does not make COM easy to understand though.

 * Essential COM - by Don Box. I like Don Box's writing style. The book starts with C++ and slowly slowly tells you why COM was needed and how is works and .... I will say this is must read book if you want to learn COM. Language is not very easy to understand (may be Don Box expect good IQ level from readers ;)). I wont recommend this book as a first book for COM.

Inside Distributed COM - Guy Eddon and Henry Eddon. Though the name says DCOM - it starts from COM and most of the book is about COM.

Inside OLE2 - by Kraig Brockschmidt. You wont understand COM better from any other book than Inside OLE2. I tried reading this book for 7 days - got frustrated at the end and left it. I want to read this book - do not know when it will be possible :(.


I will update this post when I will come across new books for Microsoft windows. Hope this post helps you. If you know any other/ better books please write a comment.

Tuesday, February 9, 2010

How to modify C++ MyString class object using visual studio debugger?

Scenario:
You are in between some serious and lengthy debugging. For doing some test you need to change string object of type MyString which contains char* and len. New string is of length shorter than original string.

Mostly the string class (Let's call it MyString) contains these data members -
1. char* m_buf => character pointer
2. int m_len => length of string

i.e. its declaration looks something like
class MyString {
public:
   // Public members
private:
    // Private data

   char* m_buf;
   int m_len;
};
After googling for few seconds I got one such sample myString class

Data:
Suppose name of string variable is "string_obj".

Required modification:
Suppose m_buf originally points to buffer "bacada", you want to to change its value to "aada"
Change the buffer, by accessing the contents of buffer using array member method -

How to do it?

First get the char* object in watch window
(string_obj).m_buf   // This will show value of pointer m_buf

To modify its contents in watch window do this (I do not find it worth to put image here)-
(string_obj).m_buf[0] = 'a'
(string_obj).m_buf[1] = 'a'
(string_obj).m_buf[2] = 'd'
(string_obj).m_buf[3] = 'a
(string_obj).m_buf[4] = 0  // Do not forget to make it null terminated string

Also do not forget to change the length variable
(string_obj).m_len = 4;

One known limitation of this hack -
You can not change the buffer of size 6 to buffer of size 8 - this can lead to crash.

Please post comment if you know better method.

Wednesday, February 3, 2010

Tools for exploring executable/ library files

For Linux -
objdump
"$ man objdump" will be best guide than any other link.


For Windows -
dumpbin

I do not want to unnecessarily waste the web space by rewriting the information already available on internet.

Few things which you with these utilities -
1. Get assembly language code from executable/ DLL.
2. Get the header information.
Explore these tools and enjoy.

I will also mention here tool called hex editor which can be used to edit a binary file :). I do not know how to use it - hope I will learn it someday.

Monday, January 25, 2010

Generating assembly code for C++ file

1. Using visual studio 2005 or 2008 :
  i. Create simple hellow world win32 console application.
 ii. Right click on the file (let's say hello.cpp) in the solution explorer tree.
iii. Select properties.
iv. Expand C/C++ in left side tree of the window raised.
 v. Click on output files under C/C++
vi. On right side of the dialog see entry in table "Assembler output", select option "Assembly with source code (/FAs)"
vii. Select OK to close this dialog.
viii. Use F7 to build the project.

In the Debug folder of your project Hello.asm (or filename.asm) should be generated.

2. Using Visual C++ 6 :
 i. Create simple hello world win32 console application.

 ii. Select the file (let's say hello.cpp) in the solution explorer tree
 iii. Select Project Menu - Settings.
 iv. Select C/C++ tab.
  v. In category select "Listing Files" from drop down.
 vi. In listing file type: drop down select "Assembly with Source Code"
vii. For Listing file name: write path as Debug/HelloWorld.asm -> this step is must unlike new Visual studio.
viii. Select OK.
viii. Use F7 to build the project.

In the Debug folder of your project HelloWorld.asm (or filename.asm) should be generated.



3. Using GCC/ G++:
Very easy compared to visual studio. :)
To generate assembly code for hello.cpp use following command -
g++ -S Hello.cpp -o Hello.S


Note:
The code generated by above options also contains many lines which you might find 'not-relevant'. To read this .asm file is your skill :).

Friday, January 22, 2010

C++ Change value of const int

This is interesting question -

I have following statement in C++ program -
const int a = 22;

and I want to change the value of a to some other value.


////////////////////////////////////////////////////////////////////////////////////////////////

I tried following code -
#include

using namespace std;

int main() {

const int a = 22;

const int *ptr_to_a = &a;
int *ptr;
ptr = (int*)ptr_to_a;

(*ptr) = 5;
cout << style="color: rgb(0, 153, 0);">// Prints 22 => Visual studio 2005 and 2008 debugger shows value of a 5!

const int &b = a;
cout << class="blsp-spelling-error" id="SPELLING_ERROR_12">endl; // Prints 5

int c = a;
cout << class="blsp-spelling-error" id="SPELLING_ERROR_14">endl; // Prints 22

return 0;
}

////////////////////////////////////////////////////////////////////////////////////////////////

Looking at the above code. I thought this problem is compiler dependent. But Visual Studio 2005 and 2008 do not give any warning, rather (I confidently dare to say that) this is bug in Visual Studio that it shows value of a 5 after "(*ptr) = 5;" (in debugger), but prints 22!
The problem is probably not compiler dependent because I got same output 22, 5, 22 using GCC (g++) compiler (I tried this on Cywgin - 32 bit Windows XP and 64 Bit Linux).

Probably the simple and logical answer to this question is - you can not change the value of "const int a".

Note I have also tried tricks like -
int *ptr = (int*)&a;
and
int *ptr = const_cast(ptr_to_a);

If you have any solution please post it in comments.