Thursday, December 27, 2012

C++ : argc and argv

So far, all the programs we have written can be run with a single command. For example, if we compile an executable called myprog, we can run it from within the same directory with the following command at the GNU/Linux command line:
./myprog
However, what if you want to pass information from the command line to the program you are running? Consider a more complex program like GCC. To compile the hypothetical myprog executable, we type something like the following at the command
line:
gcc -o myprog myprog.c
The character strings -o, myprog, and myprog.c are all arguments to the gcc command.
(Technically gcc is an argument as well, as we shall see.)
Command-line arguments are very useful. After all, C++ functions wouldn't be very useful if you couldn't ever pass arguments to them -- adding the ability to pass arguments to programs makes them that much more useful. In fact, all the arguments you pass on the command line end up as arguments to the main function in your program.
Up until now, the skeletons we have used for our C++ programs have looked something like this:

#include <iostream>
int main()
{
    return 0;
}

From now on, our examples may look a bit more like this:

#include <iostream>

int main (int argc, char *argv[])
{
    return 0;
}

As you can see, main now has arguments. The name of the variable argc stands for "argument count"; argc contains the number of arguments passed to the program. The name of the variable argv stands for "argument vector". A vector is a one-dimensional array, and argv is a one-dimensional array of strings. Each string is one of the arguments that was passed to the program.
For example, the command line
gcc -o myprog myprog.c
would result in the following values internal to GCC:
argc = 4
argv[0] = gcc
argv[1] = -o
argv[2] = myprog
argv[3] = myprog.c
As you can see, the first argument (argv[0]) is the name by which the program was called, in this case gcc. Thus, there will always be at least one argument to a program, and argc will always be at least 1.
The following program accepts any number of command-line arguments and prints
them out:

#include <iostream>

using namespace std;

int main (int argc, char *argv[])
{
    int count;
    cout<<"This program was called with \"\".\n"<<argv[0];
    if (argc > 1)
    {
        for (count = 1; count < argc; count++)
        {
            cout<<"argv[%d] = \n"<< count<< argv[count];
        }
    }
    else
    {
        cout<<"The command had no other arguments.\n";
    }
    return 0;
}

If you name your executable fubar, and call it with the command ./fubar a b c, it
will print out the following text:
This program was called with "./fubar".
argv[1] = a
argv[2] = b
argv[3] = c

Now for the explanation.

Let's say your program is named prog, and you execute it with: prog -ab -c Hello World. You
want to be able to parse the arguments to say that options a, b and c were specified,
and Helloand World are the non-option arguments.
argv is of type char **—remember that an array parameter in a function is the same as a pointer.
At program invocation, things look like this:

Here, argc is 5, and argv[argc] is NULL. At the beginning, argv[0] is a char * containing the string "prog".
In (*++argv)[0], because of the parentheses, argv is incremented first, and then dereferenced. The effect of the increment is to move that argv ----------> arrow "one block down", to point to the1. The effect of dereferencing is to get a pointer to the first commandline argument, -ab. Finally, we take the first character ([0] in (*++argv)[0]) of this string, and test it to see if it is '-', because that denotes the start of an option.

For the second construct, we actually want to walk down the string pointed to by the current argv[0]pointer. So, we need to treat argv[0] as a pointer, ignore its first character (that is '-' as we just tested), and look at the other characters: ++(argv[0]) will increment argv[0], to get a pointer to the first non- - character, and dereferencing it will give us the value of that character. So we get *++(argv[0]). But since in C, []binds more
tightly than ++, we can actually get rid of the parentheses and get our expression as*++argv[0]. We
want to continue processing this character until it's 0 (the last character box in each of the rows in the above picture).
The expression c = *++argv[0] assigns to c the value of the current option, and has the value c. while(c) is a shorthand forwhile(c != 0), so the while(c = *++argv[0]) line is basically assigning the value of the
current option to c and testing it to see if we have reached the end of the current command-line argument.
At the end of this loop, argv will point to the first non-option argument:

C++ : Access Specifier and its usage in Inheritence

There are 3 access specifiers for a class/struct/Union in C++. These access specifiers define
how the members of the class can be accessed. Of course, any member of a class is accessible within
that class(Inside any member function of that same class). Moving ahead to type of access specifiers,
they are:
Public - The members declared as Public are accessible from outside the Class through an object of the
class.
Protected - The members declared as Protected are accessible from outside the class BUT only in a
class derived from it.
Private - These members are only accessible from within the class. No outside Access is allowed.
An Source Code Example:

class MyClass
{
public:
    int a;
protected:
    int b;
private:
    int c;
};
int main()
{
    MyClass obj;
    obj.a = 10; //Allowed
    obj.b = 20; //Not Allowed, gives compiler error
    obj.c = 30; //Not Allowed, gives compiler error
}

Inheritance and Access Specifiers
Inheritance is C++ can be one of the following types:
· Private Inheritance
· Public Inheritance
· Protected inheritance

Here are the member access rules with respect to each of these:
First and most important rule Private members of a class are never accessible from
anywhere except the members of the same class.

Public Inheritance:

All Public members of the Base Class become Public Members of the derived class &
All Protected members of the Base Class become Protected Members of the
Derived Class.
i.e. No change in the Access of the members. The access rules we discussed before are further then
applied to these members.
Code Example:
class Base
{
public:
    int a;
protected:
    int b;
private:
    int c;
};
class Derived:public Base
{
    void doSomething()
    {
        a = 10; //Allowed
        b = 20; //Allowed
        c = 30; //Not Allowed, Compiler Error
    }
};
int main()
{
    Derived obj;
    obj.a = 10; //Allowed
    obj.b = 20; //Not Allowed, Compiler Error
    obj.c = 30; //Not Allowed, Compiler Error
}

Private Inheritance:
All Public members of the Base Class become Private Members of the Derived class
&A
ll Protected members of the Base Class become Private Members of the Derived
Class.
An code Example:



class Base
{
public:
    int a;
protected:
    int b;
private:
    int c;
};
class Derived:private Base //Not mentioning private is OK because for classes it defaults to private
{
    void doSomething()
    {
        a = 10; //Allowed
        b = 20; //Allowed
        c = 30; //Not Allowed, Compiler Error
    }
};
class Derived2:public Derived
{
    void doSomethingMore()
    {
        a = 10; //Not Allowed, Compiler Error, a is private member of Derived now
        b = 20; //Not Allowed, Compiler Error, b is private member of Derived now
        c = 30; //Not Allowed, Compiler Error
    }
};
int main()
{
    Derived obj;
    obj.a = 10; //Not Allowed, Compiler Error
    obj.b = 20; //Not Allowed, Compiler Error
    obj.c = 30; //Not Allowed, Compiler Error
}

Protected Inheritance:

All Public members of the Base Class become Protected Members of the derived
class &
All Protected members of the Base Class become Protected Members of the
Derived Class.
A Code Example:

class Base
{
public:
    int a;
protected:
    int b;
private:
    int c;
};
class Derived:protected Base
{
    void doSomething()
    {
        a = 10; //Allowed
        b = 20; //Allowed
        c = 30; //Not Allowed, Compiler Error
    }
};
class Derived2:public Derived
{
    void doSomethingMore()
    {
        a = 10; //Allowed, a is protected member inside Derived & Derived2 is public derivation from
        //Derived, a is now protected member of Derived2
        b = 20; //Allowed, b is protected member inside Derived & Derived2 is public derivation from
        //Derived, b is now protected member of Derived2
        c = 30; //Not Allowed, Compiler Error
    }
};
int main()
{
    Derived obj;
    obj.a = 10; //Not Allowed, Compiler Error
    obj.b = 20; //Not Allowed, Compiler Error
    obj.c = 30; //Not Allowed, Compiler Error
}

Remember the same access rules apply to the classes and members down the inheritance hierarchy.

C++ : Interface classes

An interface class is a class that has no members variables, and where all of the functions are
pure virtual! In other words, the class is purely a definition, and has no actual implementation.
Interfaces are useful when you want to define the functionality that derived classes must
implement, but leave the details of how the derived class implements that functionality entirely
up to the derived class.

Interface classes are often named beginning with an I. Here’s a sample interface class:

class IErrorLog
{
    virtual bool OpenLog(const char *strFilename) = 0;
    virtual bool CloseLog() = 0;
    virtual bool WriteError(const char *strErrorMessage) = 0;
};
 
Any class inheriting from IErrorLog must provide implementations for all three functions in
order to be instantiated. You could derive a class named FileErrorLog, where OpenLog() opens a
file on disk, CloseLog() closes it, and WriteError() writes the message to the file. You could
derive another class called ScreenErrorLog, where OpenLog() and CloseLog() do nothing, and
WriteError() prints the message in a pop-up message box on the screen.
Now, let’s say you need to write some code that uses an error log. If you write your code so it
includes FileErrorLog or ScreenErrorLog directly, then you’re effectively stuck using that kind
of error log. For example, the following function effectively forces callers of MySqrt() to use a
FileErrorLog, which may or may not be what they want.
 
double MySqrt(double dValue, FileErrorLog &cLog)
{
    if (dValue < 0.0)
    {
        cLog.WriteError("Tried to take square root of value less than 0");
        return 0.0;
    }
    else
        return dValue;
}
 
A much better way to implement this function is to use IErrorLog instead:
 
double MySqrt(double dValue, IErrorLog &cLog)
{
    if (dValue < 0.0)
    {
        cLog.WriteError("Tried to take square root of value less than 0");
        return 0.0;
    }
    else
        return dValue;
}  
 
Now the caller can pass in any class that conforms to the IErrorLog interface. If they want the
error to go to a file, they can pass in an instance of FileErrorLog. If they want it to go to the
screen, they can pass in an instance of ScreenErrorLog. Or if they want to do something you
haven’t even thought of, such as sending an email to someone when there’s an error, they can
derive a new class from IErrorLog (eg. EmailErrorLog) and use an instance of that! By using
IErrorLog, your function becomes more independent and flexible.
Interface classes have become extremely popular because they are easy to use, easy to extend,
and easy to maintain. In fact, some modern languages, such as Java and C#, have added an
“interface” keyword that allows programmers to directly define an interface class without having
to explicitly mark all of the member functions as abstract. Furthermore, although Java and C#
will not let you use multiple inheritance on normal classes, they will let you multiply inherit as
many interfaces as you like. Because interfaces have no data and no function bodies, they avoid a
lot of the traditional problems with multiple inheritance while still providing much of the
flexibility. 
 
For Abstract Classes and Pure Virtual Functions, Check this link. 

C++ : Pure virtual functions and abstract base classes

Pure virtual (abstract) functions and abstract base classes

C++ allows you to create a special kind of virtual function called a pure virtual function (or abstract function) that has no body at all! A pure virtual function simply acts as a placeholder that is meant to be redefined by derived classes.
To create a pure virtual function, rather than define a body for the function, we simply assign the function the value 0. See the example below :-

class XYZ{
    
public:
    
    void init() // A normal non-vitual function
    {
        cout<<"Initialize";
    }
    
    virtual void show() // Normal Virtual Function
    {
        cout<<"Valuse is:- " << 8;
    }
    virtual int getValue() = 0; // A Pure Virtual Function
};
 
When we add a pure virtual function to our class, we are effectively saying, “it is up to the 
derived classes to implement this function”. Using a pure virtual function has two main 
consequences: First, any class with one or more pure virtual functions becomes an abstract 
XYZ class, which means that it can not be instantiated! 

int main()
{
    XYZ xyz; // pretend this was legal
    xyz.getValue(); // what would this do?
}
 
So, we cannot create the object of an abstract class, since the 
compiler doesn't know, how much size does the class object take. 
We simply extend it. 

Second, any derived class must define a body for this function, or that
 derived class will be considered an abstract base class as well.

Let’s take a look at an example of a pure virtual function in action.

#include <string>
class Animal
{
protected:
    std::string m_strName;
    // We're making this constructor protected because
    // we don't want people creating Animal objects directly,
    // but we still want derived classes to be able to use it.
    Animal(std::string strName): m_strName(strName){
    }
public:
    std::string GetName() { return m_strName; }
    virtual const char* Speak() { return "???"; }
};
class Cat: public Animal
{
public:
    Cat(std::string strName):Animal(strName)
    {
    }
    virtual const char* Speak() { return "Meow"; }
};
class Dog: public Animal
{
public:
    Dog(std::string strName)
    : Animal(strName)
    {
    }
    virtual const char* Speak() { return "Woof"; }
};
 
We’ve prevented people from allocating objects of type Animal by making the constructor protected. 
However, there’s one problem that has not been addressed. It is still possible to create derived 
classes that do not redefine Speak(). For example:
 
class Cow: public Animal
{
public:
    Cow(std::string strName): Animal(strName)
    {


    }
// We forgot to redefine Speak
};
int main()
{
    Cow cCow("Betsy");
    std::cout << cCow.GetName() << " says " << cCow.Speak() << "\n";
}

This will print: Betsy says ???
What happened? We forgot to redefine Speak, so cCow.Speak() resolved to Animal. Speak(), 
which isn’t what we wanted.A better solution to this problem is to use a pure virtual 
function: 

#include <string>
class Animal
{
protected:
    std::string m_strName;
public:
    Animal(std::string strName):m_strName(strName)
    {


    }
    std::string GetName() { return m_strName; }
    virtual const char* Speak() = 0; // pure virtual function
}; 
 
There are a couple of things to note here. First, Speak() is now a pure virtual function. 
This means Animal is an abstract base class, and can not be instantiated. Consequently, 
we do not need to make the constructor protected any longer (though it doesn’t hurt). Second, 
because our Cow class was derived from Animal, but we did not define Cow::Speak(), Cow is also 
an abstract base class. Now when we try to 
compile this code:
 
class Animal
{
protected:
    std::string m_strName;
    // We're making this constructor protected because
    // we don't want people creating Animal objects directly,
    // but we still want derived classes to be able to use it.
    Animal(std::string strName): m_strName(strName){
    }
public:
    std::string GetName() { return m_strName; }
    virtual const char* Speak() = 0;
};


class Cow: public Animal
{
public:
    Cow(std::string strName): Animal(strName)
    {


    }
// We forgot to redefine Speak
};
int main()
{
    Cow cCow("Betsy");
    std::cout << cCow.GetName() << " says " << cCow.Speak() << "\n";
}
 
The compiler will give us a warning because Cow is an abstract base class and we can not 
create instances of abstract base classes:
 
error: C2259: 'Cow' : cannot instantiate abstract class
due to following members:
'const char *Animal::Speak(void)' : is abstract 

This tells us that we will only be able to instantiate Cow if Cow provides a body for Speak(). 
Let’s go ahead and do that:

class Cow: public Animal
{
public:
    Cow(std::string strName)
    : Animal(strName)
    {
    }
    virtual const char* Speak() { return "Moo"; }
};
int main()
{
    Cow cCow("Betsy");
    std::cout << cCow.GetName() << " says " << cCow.Speak() << endl;
}
 
Now this program will compile and print:
"Betsy says Moo"
So, A pure virtual function is useful when we have a function that we want to put in the base class,
but only the derived classes know what it should return. A pure virtual function makes it so the base 
class can not be instantiated, and the derived classes are forced to define these function before 
they can be instantiated. This helps ensure the derived classes do not forget to redefine functions 
that the base class was expecting them to.
 
For interface classes, Check this link.

Thursday, January 12, 2012

Displaying the spinner view in Google Map

For displaying the Google Map or for performing any action in Google Map go to the link:- http://mobiforge.com/developing/story/using-google-maps-android. Now here we are just displaying a spinner view in which there is the names of different countries, and on it, if you click in any country then it will display the map of that country that was clicked. The screenshots are given below for better understand.



Due to the low internet speed it is unable to display the map. Now the code is given below for performing the following operations.

MapViewActivity.java

package com.ex;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.Spinner;

public class MapViewActivity extends MapActivity implements OnItemSelectedListener {
    MapView mapView;
    Spinner mysp;
    GeoPoint p;
    MapController mc;
    String[] dataSet={"India","Australia","England","Pakistan","South Africa","Sri Lanka"};
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        mapView = (MapView) findViewById(R.id.mapView);
        LinearLayout zoomLayout = (LinearLayout)findViewById(R.id.zoom); 
        View zoomView = mapView.getZoomControls();
       
        zoomLayout.addView(zoomView,
            new LinearLayout.LayoutParams(
                LayoutParams.WRAP_CONTENT,
                LayoutParams.WRAP_CONTENT));
        mapView.displayZoomControls(true);
        mc = mapView.getController();
        String coordinates[] = {"27.000000", "78.000000"};
        double lat = Double.parseDouble(coordinates[0]);
        double lng = Double.parseDouble(coordinates[1]);

        p = new GeoPoint(
            (int) (lat * 1E6),
            (int) (lng * 1E6));

        mc.animateTo(p);
        mc.setZoom(17);
        mapView.invalidate();
        mysp=(Spinner)findViewById(R.id.spinner1);
        ArrayAdapter adapter=new ArrayAdapter(this, android.R.layout.simple_spinner_dropdown_item,dataSet);
        mysp.setAdapter(adapter);
    }

    @Override
    protected boolean isRouteDisplayed() {
        // TODO Auto-generated method stub
        return false;
    }

    public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
            long arg3) {
        // TODO Auto-generated method stub
        switch(arg2){
        case 0:
            showmap(27.000000,78.000000);
            break;
        case 1:
            showmap(35.180000,149.080000);
            break;
        case 2:
            showmap(52.450000,1.300000);
            break;
        case 3:
            showmap(30.000000,70.000000);
            break;
        case 4:
            showmap(29.000000,24.000000);
            break;
        case 5:
            showmap(37.000000,127.300000);
            break;
        default:
            break;
               
        }
       
    }

    private void showmap(Double lat,Double lng) {
        // TODO Auto-generated method stub
           mc = mapView.getController();
          
   
            p = new GeoPoint(
                (int) (lat * 1E6),
                (int) (lng * 1E6));
   
            mc.animateTo(p);
            mc.setZoom(17);
            mapView.invalidate();
       
    }

    public void onNothingSelected(AdapterView<?> arg0) {
        // TODO Auto-generated method stub
       
    }
}

The layout code is given below:-

main.xml


<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <com.google.android.maps.MapView
        android:id="@+id/mapView"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:enabled="true"
        android:clickable="true"
        android:apiKey="04gzvppWXX9dyAixd7QwUv49IJeVZl2Pqy_xfDA"
        />
      <LinearLayout android:id="@+id/zoom"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        />


      <Spinner
          android:id="@+id/spinner1"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:layout_alignParentLeft="true"
          android:layout_alignParentRight="true"
          android:layout_alignParentTop="true" />

</RelativeLayout>

AndroidMainfest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.ex"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="8" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <uses-library android:name="com.google.android.maps" /> 
        <activity
            android:name=".MapViewActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
<uses-permission android:name="android.permission.INTERNET" />
</manifest>

Thankyou. Please post your comments for the improvements.