Friday, September 28, 2012

code to illustrate static function

#include <iostream>
#include <string>
using namespace std;

class Cat
{
    public:
        static int Add(int a, int b)
        {
            return a+b;
        }
};

int main()
{
    cout << "\n" << Cat::Add(5,67) << endl;
    return 0;
}


OUTPUT:

In this example we don't have to create an object of class to access the static function.

Wednesday, September 26, 2012

What is Polymorphism

What is Polymorphism:
  • Polymorphisms is a generic term that means 'many shapes'.
  • Polymorphism is the ability (in programming) to present the same interface for differing underlying forms (data types).
  • Polymorphism describes a pattern in object oriented programming in which classes have different functionality while sharing a common interface.
  • More precisely Polymorphisms means the ability to request the same operations be Performed on a wide range of different types of things. (operator overloading)
  • Polymorphism is the ability of one object to be treated, or used, like another.

  • It is closely related to the inheritance hierarchy.
  • Function polymorphism is a kind of overloading and overriding.
  • Class polymorphism is like inheriting parent class/interface and instantiating the subclass with parent class/interface.
  • (class doesn't support polymorphism by default.) (we achieve class level polymorphism by  interface/abstract class)
  • (object doesn't support polymorphism by default; we cannot add 1 to any object) (we achieve  polymorphism in object by 'operator function')

By polymorphism we can develop new ability.  (child jab born hota hai. to vo polymorphic nature nahi rakhata, use ability di jati hai polymorphic hone ki.)

Polymorphhism in Plain English:
Noun: 1. The occurrence of something in different forms, in particular.
         2. The occurrence of different forms among the members of a population or colony.
Synonym: Multiformity

Why polymorphism:
  1. It makes our code simple (by giving polymorphic nature)
  2. U don't have remember which methode to call. (eg. multi-language SW) (function/operator overloading)
  3. To extend the behaviour of base class. (function overriding)

            The beauty of polymorphism is that the code working with the different classes does not need to know which class it is using since they’re all used the same way. A real world analogy for polymorphism is a button. Everyone knows how to use a button: you simply apply pressure to it. What a button “does,” however, depends on what it is connected to and the context in which it is used — but the result does not affect how it is used. If your boss tells you to press a button, you already have all the information needed to perform the task.
            In the programming world, polymorphism is used to make applications more modular and extensible. Instead of messy conditional statements describing different courses of action, you create interchangeable objects that you select based on your needs. That is the basic goal of polymorphism.

There are various forms of Polymorphism:
  • Function overloading: Defining multiple functions with the same name and different parameter types, such as sqrt(float), sqrt(double) and sqrt(complex). In most languages that allow this, the compiler will automatically select the correct one for the type of argument being passed into it, thus this is compile-time polymorphism.   
  • Virtual methods in OOP: A method of a class can have various implementations tailored to the specifics of its subclasses; each of these is said to override the implementation given in the base class. Given an object that may be of the base class or any of its subclasses, the correct implementation is selected on the fly, thus this is run-time polymorphism.
  • Templates: A feature of some OO languages whereby a function, class, etc. can be parameterised by a type. For example, you can define a generic "list" template class, and then instantiate it as "list of integers", "list of strings", maybe even "list of lists of strings" or the like. Generally, you write the code once for a data structure of arbitrary element type, and the compiler generates versions of it for the various element types.

Sunday, September 23, 2012

A note on Stack and Heap

  • Stack-memory and Heap-memory are physically the same.
  • The RAM may be used as stack memory when running one program and later used as heap memory when running some other program.
  • The difference is in how they are used.
Difference between Stack vs Heap memory:
 

Stack:
  • Often a function or method calls another function which in turn calls another  function etc.
  • The execution of all those functions remains suspended until the very last function returns its value.
  • All the information required to resume the execution of these functions is stored on the stack.
  • In particular, local variables are stored on the stack.
  1. Local variables are often stored for short amounts of time while a function/method block uses them to compute a task.
  2. Once a function/method has completed its cycle, the space on the stack used by all local variables is freed.
  • This chain of suspended function calls is the stack, because elements in the stack (function calls) depend on each other.
  • The stack is important to consider in exception handling and thread executions.

Heap:
  • The heap is simply the memory used by programs to store global variables. or All global variables are stored in heap memory.
  • Element of the heap (variables) have no dependencies with each other and can always be accessed randomly at any time.
  • All variables dynamically created by the program with "new()" or "malloc()" or similar commands are also stored on the heap.
  • In some programming languages, all instances of an object, including all the attributes of that instance, are stored on the heap (java).
  • In those programming languages, local variables of a function that have object type are implemented as creating the new object on the heap, and storing a reference to that object in the local variable, which is on the stack.
  • When that function exits, the heap memory used by each local variable that has object is freed, and then all the stack used by that stack is freed.

Similarties:
  • Both are used for providing memory to a program at run time.
  • both reside in main-memory (RAM)
  • both are datastructure (used to organised data)

Thursday, September 20, 2012

How to count the number of objects created of a class

#include <iostream>
using namespace std;

class Demo
{
    public:
        static int totalObject;
       
        Demo()
        {
            totalObject++;
        }
};

int Demo::totalObject(0);    //static variable initialized to 0

int main()
{
    Demo d1;
    Demo d2;
    Demo d3;
    Demo d4;
   
    cout << "\n Total no of object of Demo class is: " << Demo::totalObject << endl;
    return 0;
}


OUTPUT:

Wednesday, September 19, 2012

Program to display all prime fibonacci series, between 1 to 10000

#include<iostream>
#include<cstdio>
using namespace std;

int isprime(int);

int main()
{
    cout << "\n All prime fibonacci series in the range of 1 to 10000 are" << endl;
    int r;
    int a = 1,b = 2,c = 0;
    r = isprime(a);
    if (r == 1) cout << a <<" ";
    r = isprime(b);
    if (r==1) cout << b <<" ";
    while (c <= 10000)
    {
        c = a+b;
        r = isprime(c);
        if ((r == 1) && (c <= 10000))
        cout << c <<" ";
        a = b;
        b = c;
    }
    return 0;
}

int isprime(int x)
{
    int i;
    if (x == 1) return 0;
    else
    {
        int p = 1;
        for(i=2; i<x; i++)
        {
            if (x%i==0)
            p=2;
        }
        return (p);
    }
}


OUTPUT:

Friday, September 14, 2012

What is library and List of c++ libraries

What is a library:
  • A library is a collection of implementations of behavior, written in terms of a language, that has a well-defined interface  by which the behavior is invoked.
  • Behavior is provided for reuse by multiple independent programs.
  • A program invokes the library-provided behavior via a mechanism of the language.
 
What is the advantage of library:
  • A library provide the reuse of the behavior. When a program invokes a library, it gains the behavior implemented inside that library without having to implement that behavior itself. 
  • Libraries encourage the sharing of code in a modular fashion, and  ease the distribution of the code. 

There are two type of library:
 1. Static library

  • If the code of the library is accessed during the build of the invoking program, then the library is call a static library.
 2. Dynamic library
  • The library behavior is connected after the executable has been invoked to be executed, either as part of the process of starting the execution, or in the middle of execution. In this case the library is called a dynamic library. 
  • A dynamic library can be loaded and linked as part of preparing a program for execution, by the linker.
                  
What is linker:
A computer program that takes one or more objects generated by a compiler and links them to standard library function and hence making them executable program.
   The linking process is usually automatically done by a linker or binder program that searches a set of libraries and other modules in a given order. Usually it is not considered an error if a link target can be found multiple times in a given set of libraries. Linking  may be done when an executable file is created, or whenever the program is used at run time.


For more detail on What is linker click here


      Free portable C++ libraries that complement the C++ Standard Library. Many Boost libraries may become part of the next C++ Standard.


             A comprehensible list of open source C++ libraries. So that you doesn't need to waste time searching on Google. 

Wednesday, September 12, 2012

Program to illustrate 'typedef' keyword

#include <iostream>
using std::cout;
using std::endl;

typedef float FLOAT32;
typedef double FLOAT64;     //
By using typedef Keyword we can make alias of datatypes
typedef unsigned int U32;    //it is something like macro

int main()
{
    U32 bigint = 23433;
    FLOAT32 myFloat = 6.6;
    FLOAT64 myDouble = 34343.3;
   
    cout << "  bigint: " << bigint;
    cout << "\n myFloat: " << myFloat;
    cout << "\nmyDouble: " << myDouble;
}


what is typedef:
typedef is a keyword in the C and C++ programming languages. The purpose
of typedef is to assign alternative names to existing types

what is the use of typedef keyword:

1) it provides a means to make a program more portable. Instead of having to
    change a type everywhere it appears throughout the program's source 

    files, only a single typedef statement needs to be changed.
2) A typedef can make a complex declaration easier to understand. 


By using typedef Keyword we can make alias of datatypes

Tuesday, September 11, 2012

How to make abstract class in c++

C++ has no abstract keyword or equivalent, to make a class abstract is to declare a pure virtual function in it (which prevents instantiation).

For this same reason, in C++ there is not much difference between an  interface and an abstract class - a C++ interface is simply a class containing only pure virtual functions.

C++ has no keyword abstract. However, you can write pure virtual functions; that's the C++ way of expressing abstract classes.

What is a Pure Virtual Function:
A Pure Virtual Function is a Virtual function with no body.

Declaration  of Pure Virtual Function:
Since pure virtual function has no body, the programmer must add the notation =0 for declaration of the pure virtual function in the base class.

Syntax of Pure Virtual Function:
class class_name //This denotes the base class of C++ virtual function
{
    public:
    virtual void virtualfunctioname() = 0 //This denotes the pure virtual function in C++
};

___________________________________________________________________
//Full code example
#include <iostream>
using namespace std;
class Sandeep
{
public:
        virtual void example()=0; //Denotes pure virtual Function Definition
};

class Demo1:public Sandeep
{
public:
        void example()
        {
                cout << " \n Welcome";
        }

};

class Demo2:public Sandeep
{
public:
        void example()
        {
                cout << " To My blog \n";
        }

};

int main()
{
        Sandeep* arra[2];
        Demo1 d1;
        Demo2 d2;
        arra[0]=&d1;
        arra[1]=&d2;
        arra[0]->example();
        arra[1]->example();
}


OUTPUT:

Thursday, September 6, 2012

Program to check ARMSTRONG number in c++

// program to check the armstrong number

#include <iostream>
using namespace std;

int main()
{
   int num, sum = 0, temp, remainder;

   cout << "Enter a number to check: " << endl;     
   cin >> num;

   temp = num;

   while( temp != 0 )
   {
      remainder = temp%10;
      sum = sum + remainder*remainder*remainder;
      temp = temp/10;

   }

   if ( num == sum )
      cout << "Your Number is an armstrong number." << endl;
   else
      cout << "Your Number is not an armstrong number." << endl;      
}

___________________________________________________________________________________

//program to generate armstrong number

#include <iostream>
using namespace std;

int main()
{
   int r;
   long long number = 0, c, sum = 0, temp;

   cout << "Enter the maximum number upto which you want to find armstrong numbers ";
   cin >> number;

   cout << "Following armstrong numbers are found from 1 to " << number << endl;

   for( c = 1 ; c <= number ; c++ )
   {
      temp = c;
      while( temp != 0 )
      {
         r = temp%10;
         sum = sum + r*r*r;
         temp = temp/10;
      }


      if ( c == sum )
         cout << c << endl;
      sum = 0;
   }
}

Monday, September 3, 2012

How do I create an instance of a class?

The methods called when a class is created are called contructors. There are four possible ways of specifying constructors; the fifth method is worth mentioning for clarifying reasons:
  • default constructor
  • copy constructor
  • value constructor
  • conversion constructor
  • copy assignment (not a constructor)
struct A
{
  A() { /* ... */ }                          // default constructor 
  A(const A &a) { /* ... */ }                // copy constructor 
  A(int i, int j) { /* ... */ }              // value constructor 
  A     &operator=(const A &a) { /* ... */ } // copy assignment 
};

struct B
{
  B() { /* ... */ }           // default constructor
  B(const A &a) { /* ... */ } // conversion constructor 
};

void    function()
{
  A     a0(0, 0); // shortcut, value constructor 
  A     a1(a0);   // shortcut, copy constructor 
  B     b1(a1);   // shortcut, conversion constructor 
  B     b;        // shortcut, default constructor 

  b1 = a0;        // conversion contructor 
  a0 = a1;        // copy assignment 
}

Saturday, September 1, 2012

Polymorphism in c


operator overloading--  c support;                  c++ also support
function  overloading--  c doesn't support;       c++ support

c support operator_overloading but not Function_overloading
c++ support operator_overloading as well as Function_overloading

What is operator overloading:
                               operator overloading is a specific case of polymorphism, where  operators  have different implementations depending on their arguments. 
(The whole idea in operator overloading is 'same operator' and 'different type argument')

what is Function overloading: 
                            Function overloading or method overloading is a feature in programming language that allows creating several methods with the same name which differ from each other in the type of the input and the output of the function. 
(The whole idea in function overloading is 'same function name' and 'different type argument')


As we known 'int' and 'float' are different datatype, instead of using different operator to add 'int' and 'float'; we use a common operator (+), this is known as operator overloading.


Program to shows, C support operator overloading
program to shows, cpp support operator overloading

____________________________________________________________________________
Program to show, c doesn't support Function overloading 
#include <stdio.h>
#include <conio.h>

// volume of a cube
int volume(int s)                         //Name of this function is 'volume'
{
    return(s*s*s);
}

// volume of a cylinder
double volume(double r, int h)      
//Name of this function is also 'volume' 
{
    return(3.14*r*r*h);
}

// volume of a cuboid
long volume(long l, int b, int h)     //Name of this function is also 'volume'
{
    return(l*b*h);
}

int main()
{
    cout << volume(10)        << endl;
    cout << volume(2.5,8)     << endl;
    cout << volume(10,5,15)  << endl;
}
  • when we compile this program it give error, because c doesn't support 'function overloading.'
  • जब c compiler 3 same name (volume) के फंक्शन देखता है तो कंफ्यूज हो जाता है। क्योकि c का compiler Function overloading (polymorphism) नहीं जनता, इसलिए तो  कहते है, c Function overloading support नहीं करती।

_________________________________________________________________________________
But c++ Function overloading support करती है
Program to show, cpp support Function overloading 
#include <iostream>
using namespace std;

// volume of a cube
int volume(int s)                         //Name of this function is 'volume'
{
    return(s*s*s);
}

// volume of a cylinder
double volume(double r, int h)      
//Name of this function is also 'volume' 
{
    return(3.14*r*r*h);
}

// volume of a cuboid
long volume(long l, int b, int h)     //Name of this function is also 'volume'
{
    return(l*b*h);
}

int main()
{
    cout << volume(10)       << endl;
    cout << volume(2.5,8)    << endl;
    cout << volume(10,5,15) << endl;
}
 

This program run and
OUTPUT IS:
1000
157
750 
_________________________________________________________________