Thursday 23 May 2013

Introduction of OOPs and Revision of basics


History of programming approaches
l  At each critical point in the evolution of programming, a new approach was created to help the programmer handle increasingly complex programs.
l  The first programs were created by toggling switches on the front panel of the computer.
l  This approach is suitable for only the  smallest programs
l  Next, assembly language was invented, which allowed longer programs to be written. 
l  The next advance happened in the 1950s when the first high level language (FORTRAN) was invented.
l  By using high level programming language, a programmer was able to write programs that were several thousand lines long. However the method of programming was ‘anything’ goes approach. It yields unreadable and unmanageable code.
l  Next invention is structured programming languages in the 1960s
l  C is a structured programming language as it contains control structures, code blocks and absence of goto (or at least minimal use)
l  To allow more complex programs to be written, a new approach of programming is needed. So the object oriented programming was invented.
l  OOP takes the best of the ideas embodied in structured programming and combines them with powerful new concepts that allow you to organize your program more effectively.

Inventions of programming languages
l  In 1940s, Assembly language was invented which is a machine level language; also it comes under low level language.
l  In 1950s, FORTRAN was invented. It is first high level programming language that is machine independent language.
l  In 1966, BCPL was invented by Martin Richards. BCPL stands for Basic Combined Programming Language.
l  In 1969, B language was developed by Ken Thompson. He is also know as developer of UNIX operating system.
l  In 1972, C language was developed by Dennis Ritchie at AT &T’s Bell Lab, New Jersy USA.
l  In 1979, C++ language was developed by Bjarne Stroustrup. Initially C++ was pronounced as C with classes.

Some Points about C++
l  C++ was developed by Bjarne stroustrup in the year 1979 at AT and T’s Bell Labs, New Jersey USA.
l  C++ is an enhancement in C, so it consists of all the features that C provides.
l  Initially C++ was known as ‘C with classes’.
l  In the year 1983, it is named as C++.
l  C++ is also a middle level language just like C.

Differences between C and C++

1) When a function takes no parameter, its prototype has the word void inside parenthesis.
int fun(void);
However, in C++ the void is optional.
int fun();
If this convention would use in C, it mean that nothing is said about the parameters.

2) In a C++ program, all functions must be prototyped. In C, prototypes are recommended but technically optional.

3) About keyword return:
In C++, if a function is declared as returning a value, that is return type other than void, any return statement within that function must contain a value.
In C, a non void function is not required to actually return a value. If it doesn’t, a garbage value is returned.

4) Comments:
In C, comments in the program can be specified by /*….*/
In C++, due to backward compatibility, /*….*/ is still used for multiple line comments. We can also make a single line as comment by prefix that line by //

5) Declaration of local variables
In C local variables can be declared only at the start of a block prior to any action statements.
In C++ local variables can be declared anywhere in the block.

6) Reference variable
In C++, reference variable are implicit pointers that acts as another variable name for some existing variable. There is no concept of reference variable in C.

7) Top Down and Bottom up approach
C programmer follows top down approach for programming
It is a program design technique that starts with the highest level of an idea and works its way down to the lowest level of detail.
C++ programmer adopts bottom up approach for programming.
In a bottom-up approach the individual base elements of the system are first specified in great detail. These elements are then linked together to form larger subsystems, which then in turn are linked, sometimes in many levels, until a complete top-level system is formed.

8) Procedure oriented Programming and Object Oriented Programming
Procedure oriented Programming
Main program is divided into small parts depending on the functions.
The Different part of the program connects with each other by parameter passing. Most of the functions use global data.
Object Oriented Programming
Main program is divided into small objects depending on the problem.
Data & functions of each individual object act like a single unit.
Each object controls its own data.
Data hiding is possible in OOP which prevent illegal access of function from outside of it. This is one of the best advantages of OOP
Input/Output Instruction
In C, standard input device is keyboard and scanf() is use to receive data from keyboard.
Also, standard output device is monitor and printf() is use to send data/message to monitor.
In C++, printf() can be replaced by ‘cout’:
l  cout<<”Hello ”;
l  This statement introduces two new C++ features, cout and <<.
l  cout is a predefined object.
l  The operator << is called the insertion or put to operator
l  It is used to display message on the screen.
Examples:
printf(“Hello ”);
cout<<“Hello ”;

printf(“sum of %d and %d is %d”, a, b, c);
cout<<“sum of ”<<a<<“ and “<<b<<“ is “<<c;

printf(“%d”,a+b);
cout<<a+b;

In C++, scanf() can be replaced by ‘cin’:
l  cin>>x;
l  cin>>y>>z;
l  The identifier cin is a predefined object in C++
l  The operator >> is known as extraction or get from operator
l  It is used to take input from keyboard.
Examples:
scanf(“%d”, &a);
cin>>a;
scanf(“%d%d”, &a, &b);
cin>>a>>b;

scanf(“%d%f”, &a, &c);
cin>>a>>c;

About header file iostream.h
We need to include header file iostream.h, as it contains declarations for the identifier cout and the operator <<.  Also it contains declarations for the identifier cin and operator >>.

Sample Program
#include<iostream.h>
void main()
{
            int x, s;
            cout<<”Enter a number”;
            cin>>x;
            s=x*x;
            cout<<”Square of “<<x<<” is “<<s;
}

Functions in C++


About main function
l  In C++, default return type of main function is int.
l  In C++, if a main function is not prefixed by any return type then it is assumed as int. In such cases if you do not return any int value by using keyword return, a warning occurs during compilation- “Function should return a value”. This situation can be avoided by using return keyword in main or use void before main.
Function Prototype
l  The prototype describes the function interface to the compiler by giving details such as the number and type of arguments and type of return values.
 Its syntax is
      return type function name (argument list);

l  Function prototype is also known as function declaration.
l  If a function is declared outside any function that is globally, then function can be called from any part of the program.
l  If a function is declared inside a particular function, then it is called local declaration. This means function can be only called from the function where it is declared.

Function Call by Value
l  A function call by passing values
l  The called function creates a new set of variables and copies the values of arguments into them.
l  This mechanism is good if the function does not need to alter the values of the original variables in the calling program.

#include<iostream.h>   //header file contains declaration of cout and cin
int area(int,int);             // function declaration/prototype
void main()
{
  int l, b, a;
  cout<<“Enter length and breadth”;
  cin>>l>>b;
  a=area( l , b);              //function area() is called by passing two int values
  cout<<“Area of rectangle is “<<a;
}
int area(int L, int B)      //function definition
{
 return(L*B);
}

l  Here function area() is called by passing two int values, that is mentioned by writing variable names separated by comma in parenthesis.
l  Values of l and b are copied into variables L and B respectively.
l  Function can only access its own variables, therefore function area() cannot access l and b. This is the reason we copy value of l and b in L and B.
l  Function area() returns a value produced by product of L and B. This value is then stored in variable ‘a’ of function main().

Function call by passing address
l  There may some scenarios where we would like to change the values of variables in the calling program.
l  Addresses can always be stored in special variables called pointers.

#include<iostream.h>
main()
{
 int a,b;
 void swap(int *, int *);
 cout<<“Enter two numbers: “;
 cin>>a>>b;
 swap(&a,&b);
 cout<<“a=“<<a<<” b=“<<b;
}
void swap(int *p, int *q)
{
 int t;
 t=*p;
 *p=*q;
*q=t;
}

l  Above program is of swapping the contents of two variables ‘a’ and ‘b’.
l  Notice the function call swap(&a, &b), here we pass addresses of variables ‘a’ and ‘b’ in place of values as we want to make changes possible in variable ‘a’ and ‘b’ from function swap().
l  These addresses get collected in pointers p and q.
l  swap () function returns nothing as it can directly makes changes in variables a and b using pointers p and q.

Function call by reference
l  A reference is implicit pointers that for all intents and purpose act like another name for a variable.
l  C++ permits us to pass parameters to the functions by reference.
l  The formal arguments in the called function become aliases (alternative name) to the actual arguments.
#include<iostream.h>
void main()
{
 int a,b;
 void swap(int &, int &);
 cout<<“Enter two numbers: “;
 cin>>a>>b;
 swap(a,b);
 cout<<“a=“<<a<<” b=“<<b;
}
 void swap(int &x, int &y)
{
 int t;
 t=x;
 x=y;
 y=t;
}

l  Here, function swap() is called by passing references of variable ‘a’ and ‘b’.
l  x and y are reference variables that is another names of ‘a’ and ‘b’ respectively
l  So we do not create extra copies of ‘a’ and ‘b’. 

Inline function
l  Function in a program is to save memory space which becomes appreciable when a function is likely to be called many times.
l  However every time a function is called, it takes lot of extra time in executing a series of instructions for tasks such as jumping to the functions, saving registers, pushing arguments into the stack and returning to the calling function.
l  So when function is small it is worthless to spend so much extra time in such tasks in cost of saving comparatively small space.
l  To eliminate the cost of calls to small functions, C++ proposes a new feature called inline function.
l  An inline function is a function that is expanded in line when it is invoked.
l  Compiler replaces the function call with the corresponding function code.
l  inline is a request not a command.
l  The benefit of speed of inline functions reduces as the function grows in size.
l  So the compiler may ignore the request in some situations.
Few of them:
·        Function containing loops, switch, goto.
·        Functions with recursion
·        Containing static variable.

#include<iostream.h>
inline int add(int, int);
void main()
{
  int a,b;
  cout<<”Enter two numbers”;
  cin>>a>>b;
  int sum=add(a, b);
  cout<<”Sum is “<<sum;
}
int add(int x, int y)
{  return(x+y); }


Default arguments

l  C++ allows us to call a function without specifying all its arguments. In such case function assigns a default value to the parameter which does not have a matching argument in the function call. Default values are specified when the function is declared.
#include<iostream.h>
int add(int,int,int z=0);
void main()
{
  int a,b,c;
  cout<<”Enter three numbers”;
  cin>>a>>b>>c;
  int s3=add(a,b,c);
  cout<<s3;
  int s2=add(a,b);
  cout<<s2;
}
int add(int x,int y,int z)
{
  return(x+y+z);
}

l  The default value is specified in a manner syntactically similar to a variable initialization. The above prototype declares a default value of 0 to the argument z.
l  Here, we have only one version of function add, which is capable of taking three arguments as well as two arguments.
l  When function add() has two parameters, then first value is received in x, second value is received in y and there is no value for z but z is by default containing 0.

Function overloading

l  Overloading refers to the use of same thing for different purposes. Function overloading means, we can use the same function name to create functions that perform a variety of different tasks. This is called function polymorphism or compile-time polymorphism in OOP. Another is run time polymorphism which we’ll discuss later
l  The correct function to be invoked is determined by checking the number and type of the arguments but not on the function type (return type).

#include<iostream.h>-
float area(int);
int area(int,int);
void main()
{
  int  r;
  cout<<”Enter radius of a circle”;
  cin>>r;
  float a=area(r);    
  cout<<”Area of circle is “<<a;
  int l,b,A;
  cout<<”Enter length and breadth of rectangle”;
  cin>>l>>b;
  A=area(l,b);
  cout<<”Area of rectangle is “<<A;
}
float area(int R)
{ return(3.14*R*R); }
int area(int L, int B)
{ return(L*B); }

Structure in C++


Structure in C
l  Structure is a collection of dissimilar elements.
l  Structure is a way to group variables.
l  Structure is way to create user defined data type

sruct book
{
  int id;
  float price;
  char title[20];
};

l  Here, book is a user defined data type.
l  In above example, structure book is a group of three variables id, price and title.
l  We can easily understand that these variables are of different type.
l  Do not forget to put semicolon at the end of structure body.
l  Till the structure is only defined and not actually used to create variables, no space is allocated for these variables.
l  When defining structure, mentioning variables in structure body is not actually creating variables (hence no memory consumed), instead we are just defining a memory model for those variables that could be created using data type book.

Creating structure variables

sruct book
{
  int id;
  float price;
  char title[20];
};

main()
{
  struct book b1,b2;
  …
  …
}

l  Here, we declare two variables of type book.
l  Each variable b1 and b2 will consume 26 bytes of memory space (i.e. sum of the memory consumed by member variables)
l  In C, keyword struct should always be prefixed during each use of such user defined data type.

Accessing members of structure

sruct book
{
  int id;
  float price;
  char title[20];
};
main()
{
  struct book b1,b2;
  printf(“Enter id, price and title of book”);
  scanf(“%d%f”,&b1.id, &b1.price);
  gets(&b1.title[0]);
  b2=b1;
  …
  …
}

l  Variables b1 and b2 both are of type book consuming 26 bytes each, containing three variables: id, price, title.
l  Members cannot be accessed freely, it should always be prefixed with variable of book type and dot( . ) operator.
l  We can copy the contents of b1 in b2, as shown in the above example. This helps an easy access to group of variables. No need of copying each and every element one by one.

Differences between structures of C and C++

l  In C++ a structure can have both variables and functions as members. In C a structure can have only variables as members.
l  In C++ members can be private, protected or public but in C there is no facility of access specifiers (Private, protected and public are access specifiers and we will discuss them in the next segment).
l  In C++, a structure can have inheritance. On the other hand in C a structure does not support inheritance.
l  In C++, the struct keyword can be omitted in the declaration of structure variables, but in C, the struct keyword is mandatory during the use of structure defined data-type.
Example:
#include<iostream.h>
struct complex
{
     private:
     int a;
     int b;
     public:
     void getdata()
     {
          cout<<”Enter two numbers”;
          cin>>a>>b;
     }
     void showdata()
     {
          cout<<”a=”<<a<<”b=”<<b;
     }
};
void main()
{
  complex c1,c2;
  c1.getdata();
  c2.getdata();
  c1.show();
  c2.show();
}


l  In C++, structure may contain functions along with variables as members.
l  Here, we defined four members; two are member variables (a and b) and two are member functions (getdata() and showdata())
l  Notice that we define member variables with access specifier private. Also, member functions with access specifier public.
l  Those members are private, cannot be accessed from outside the structure body.
l  Those members are public, can be accessed from outside the structure.
l  We can define structure in C++ exactly in the same way as we do in C. This is due to support backward compatibility.
l  If we do not mention any access specifier for members of structure, then it is assumed public.

Class and Structure in C++ are similar

l  Just replace the keyword struct with keyword class.

#include<iostream.h>
class complex
{
     private:
     int a;
     int b;
     public:
     void getdata()
     {
          cout<<”Enter two numbers”;
          cin>>a>>b;
     }
     void showdata()
     {
          cout<<”a=”<<a<<”b=”<<b;
     }
};
void main()
{
  complex c1,c2;
  c1.getdata();
  c2.getdata();
  c1.show();
  c2.show();
}

l  You can very well understand that the definition style and accessing methods of class members are exactly same as we did in structure example.
l  The only difference between class and structure in C++ is that by default the members of a class are private; on the other hand, by default the members of a structure are public.
l  A class is a way to bind the data and its associated functions together. (encapsulation)
l  In C++, class and structure both allows the data and functions to be hidden, if necessary, from the external use. (data hiding)
l  In C++, when defining a class or structure, we are creating a new abstract data type that can be treated like any other built in data type.

A common question arises why concept of class exist when structure fulfill all the requirements. The strong reason concerns maintaining upward compatibility from C. In C++, a C-style structure is also perfectly acceptable in a C++ program. Since in C all structure members are public by default, this convention is also maintained in C++. Further because class is syntactically separate entity from struct, the definition of a class is free to evolve in a way that will not be compatible with a C like structure definition. Since the two are separated, the future direction of C++ is not restricted by compatibility concerns.