Friday, 18 September 2015

Notes On C++

HISTORY OF C++

C++ was developed by Bjarne Stroustrup at AT&T Bell Laboratories in Muarry HIl,New Jersy (USA) in 1983.The version 1.0 of  C++ became commercially available in 1982,version 2.0 in 1989 and version 3.0 in 1992.Before for evolution of Object Oriented language C++,many other object oriented language exixted.

Evolution of Object Oriented Programming Approach

The various categories of programming approaches are classified as follows.

a) Monolithic Programming Approach.
b) Procedural Programming Approach.
c) Structured  Programming Approach.
d) Object Oriented Programming Approach.

Monolithic Programming Approach

In Monolithic Programming Approach the program consist of sequence of statements that modify data which is global throughout the whole program.The Program control is achieved through the use of jumps (i.e. goto statements) and code is duplicated each time as there is no support for the function.Data is not fully protected.So this approach is usefull for developing small and simple programs.The programming languages like ASSEMBLY and BASIC follow this approach.

Procedural Programming Approach 

Procedural Programming Approach is top down approach in which program is divided into functions that perform a specific task.Data is global and all the functions can access the global data.Program flow control is achieved throw the use of jumps and function calls.This approach avoid the repetition of code.The programming languages like FORTRAN and COBOL follow this approach.

  

Structured  Programming Approach


The basic principal of  Structured  Programming Approach is to divide a program into functions and  modules.Each module has set of related functions.The programming languages like PASCAL and C follow this approach.

Object Oriented Programming Approach

The Object Oriented Programming Approach came to remove some of the flaws encountered int procedural approach for designing large and complex programs.The basic principal of Object Oriented Programming Approach is to combine both data and functions that operate on that data into a single unit.Such a unit is called an object.















Basic concepts of  object-oriented programming

It is necessary to understand some concepts used extensively in object-oriented programming.
  • Objects
  • Classes
  • Data abstraction and encapsulation
  •  Inheritance
  • Polymorphism
  • Dynamic binding
  • Message passing

Object

Objects are the basis run time entities in the object oriented system.They may represent a person, a place,a bank account and any item that program has to handle.They may also represent a user-defined data such as lists and time.Program objects should be chosen such that they match closely with the real-world objects.Object take up space in memory and have associated address like a record in pascal,or a structure in c.
When a program is executed,the objects interact by sending messages to one other.For example if "customer" and "account" are two objects in a program then the customer object may send a message to the account object requesting for the bank balance.Each object contains data and code to manipulate the data.Objects ca interact without having to know details of each other's data or code.It is sufficient  to know the type of message accepted, and the type of response returned by the objects.

Class

A class is a collection  of same type of objects having same attributes and common behaviours.It is just template or blueprint to create object.
Consider an example of an object you.Now you certain attributes like your age ,name,height  etc and certain behaviours like you have some style like walking,speaking.Similarly your friends Rajveer , Sukdav, Amit also certain  attributes like age,name,height etc and certain behaviours like walking,speaking.All these people represents different objects having same attributes and common behaviours.So all these objects can be grouped together a class person.

Class person
age                   (attributes)
name                (attributes)
height               (attributes)
walking()           (Functions)
speaking()         (Functions)

objects:-You(person),Rajveer(person),Sukdav(person),Amit(person)

Data Abstraction and Encapsulation

The wrapping up of data and functions into a single unit is known as encapsulation.Data encapsulation is the most striking feature if a class.The data is not accessible to the outside world,and only those functions which are wrapped in the class access it.The functions provide the interface between the objects's data and the program.This insulation of the data from direct access by the program is  called data hiding.

Abstraction is process that involves the identification essential features without knowing the internal detail of a function.Abstraction mange complexity of a program.Classes use the concept of abstraction and are defined as a list of abstract attributes such as size,weight and cost and functions to operate on these attributes.
Since the classes use the concept of data abstraction,they are know as Abstract Data Types (ADT).


Inheritance

Inheritance is process of driving new class  from an existing class without modify itThis is known as derived class,Sub class,Child class.

In OPP,the concept of inheritance provides the idea of reusability.This means that we can add additional features to an existing class without modifying it.This is possible by deriving a new class from the existing class.The new class will have the combined features of the both the classes.


Polymorphism

Polymorphism is av very powerful concept that allows the designing of amazingly flexible applications.The word Polymorphism is derived from two Greek words Poly which means many and morphos which means forms.So,Polymorphism means the ability to take many forms.
Polymorphism can be defined as ability to use the same name for two or more related  but technically different tasks.In other words,Polymorphism can be defined as one interface that can be used to perform related but different tasks.For example,in C language to perform the addition of two integers or floating point numbers we need three separate functions (like sum_int(),sum_float()) for performing these two tasks.This is because C language does not support Polymorphism.But in case of C++ which supports Polymorphism,each function can be called by the same name such as sum().

Dynamic binding

Binding refer to the linking of a function call to the code of the function to be executed in response to the function call.

Binding is of two types
a) Static Binding :- In Static Binding, the linking of a function call to the code of the function to be executed in response to the function call is made at the compile time.
b) Dynamic Binding :-In Dynamic Binding, the linking of a function call to the code of the function to be executed in response to the function call is made at the run time.

Message passing

In Object Oriented Programming (OOP) different objects communicate with each other using the concept of message passing.Objects communicate with one other by sending and receiving informination much the same way as people pass messages to one another.The concept of message passing makes it easier to talk about building systems that directly model or simulate their real-world counterparts

Advantages of OOPs

  1. Data Security (Data Hinding & Abstraction)
  2. Improve Maintaiance & Modification
  3. Reusability
  4. OOPs is well suitable for Modelling Real word problem.
  5. Reduce complexity
  6. OOPs provide the facility of creating multiple objects of a class.
  7. Easy to locate and remove bugs and error.


Tokens

As we know,the smallest individual units in a program are known as tokens.Tokens is smallest unit which is easily identifies by C++ compiler.C++ has the following tokens:
  • Keywords
  • Identifiers
  • Constants
  • Strings
  • Operators

 Keywords

Keyword is reserve word that have predefine meaning.Keyword is a word whose meaning is already define to C++ compiler.Keywords can be written is lower case.
Ex:- int,float,double etc.

All C keywords are valid in C++ Keywords.But C++ also contain extra keywords.Ex:- Public,Private,True,False etc.



Identifiers

 Identifiers refer to the names of variables,Functions,arrays,classes etc.,created by the programer.They are the fundamental requirement of any language.Each language has its own rules for naming these identifiers.

Rules

  1. Identifiers name also start from alphabet.
  2. No blank space allow between two words.
  3. No special character is allow.
  4. Two words are join with the help of underscore.
EX:- Valid  sum and invalid 4sum.

Variables

Variables is a name that is used to by computer memory to store a value used in a program.

Ex:- a,name, sum etc.

Constants

Contants refer to fixed value that do not change during the execution of a program.
Like C,C++ supports several Kinds of literal constants,They include integers,characters,floating
point number and strings.

Integer constants :- An integer is a whole number without decimal point.It consists of sequence of digits.An integer constants must lie within the range of integer.They can be written in three different number systems:Decimal(base 10),Octal(base 8),Hexadecimal(base 19).

Ex- Valid 23 and Invalid 2,3 .

Floating point constants :- Floating point constants are used to represent real number.It contain decimal point or an exponent sign.

Ex:- 23.35 ,50.78

Character constants :- Character constants is always enclosed in a single (' ').It may be any alphabet,special character ,Digit.Do not be blank space.

Ex:- 'S','1'

String constants :- String constants is always enclosed in a double cotes (" ").It may be any alphabet,special character,digits.

Ex:- "Hello","12345"



 

Functions

A function is a self contain set of statements that perform a specific task.With the help of function larage program is divided into small program called function. main() is an example of user-defined function and strev(),sin() etc is an example of library function.

Advantages of function

  1. With the help of function larage program is divided into small program is called function. 
  2. Remove error more easily. 
  3. Reduce the repetition of code.
  4.  Reduce the complexity of a program.

 Types of function

C++ functions can be classified into two categories, namely library function and user-defined functions.main() is an example of user-defined function and sin(),cos() etc. is an example of library function.

  • Library Function
  • User-defined Function 
  1. Library function :-  There are certain set of general purpose operations which are quite frequently used by many programmers in their programs.For example- To calculate the square root of a number,to calculate power of number and many more.
    The  library functions are predefined functions which are designed to perform some specific tasks.Before using library function in the program, it is necessary to include header files.The header file contain the information about library functions.  The library  functions that perform mathematical operations.Ex:- sin(),cos() etc.They are include math.h header file.The library  functions that perform string operations.Ex:-strev,strcmp() etc.They are include String.h header file.
  2. User-defined functions:-These functions which are defined by the user to meet his requirements are called user-defined functions. Every C++ program contain atleast one function.The function which is present in every C++ program is main( ) which is user-defined function.The library and user-defined functions are normally used in the main() function.
Every function in C++ consists of following components
a)   Function Definition
b)  Function declaration
c)  Function call

Function Definition

Function definition contain the actual code of a function.The general syntax of function definition is

ret_type func_name(data_type par1,data_type par2,..........)
{
local variable declaration;
statement1;
........................
........................
return(expression);
}

The first line of function  definition is called the function declarator that consists of ret_type which specific the data type of the value to be  returned,func_name which specifies the name of the function and set of parameters and their data type separated by commas enclosed in pair of parentheses

Function declaration

While using library functions in the program, it is necessary to include the header file which contains the declaration of related library function.Similarly in C++,it is unavoidable to use a user-defined function   without its declaration.Infact ,before a  function can be called,it must be declared in the function that will do the calling. A function declaration specific the name of the function,number and type of the parameters and its return type followed by a semicolon.

The syntax of function declaration is as follows :  

ret_type func_name(data_type par1,data_type par2,..........);

Here,the ret_type specifies the data type of the value returned by the function.If  the function does not return any value.The func_name is any valid identifier which is followed by list of  parameter(s) preceded by their data types separated by commas and enclosed in parentheses.

Function call

A function which is declared and defined needs to be used somewhere in the program so that it can perform its intended task for which it is designed.In order to use it in the program,we need to call it.A function can be called by specifying the function name followed by a list of arguments separated by cooms enclosed in the pair of parentheses.

 Program of using function addition of two number

#include<iostream.h>
#include<conio.h>
main()
{
int num1=10,num2=20;
clrscr();
void add(int,int);           //Function declaration
add(num1,num2);        //Function call
getch();
}
void add(int x,int y)    //Function definition
{
int sum=x+y;
cout<<"Sum="<<sum;
}

Output of this program
Sum=30

Argument Passing Technique

Argument passing is a process of transfer data from calling function to called function.

Pass argument in three different ways

  • Pass by value
  • Pass by address or pass by pointer
  • Pass by refference
  •   Pass by value :- Pass by value is a technique used for argument passing.In this technique copy of actual argument is made and pass to the formal argument.Any change made in the formal argument  are not refer back to the actual argument.
Program using Pass by value technique swap two number        
#include<iostream.h>
#include<conio.h>
main()
{
int num1=10,num2=20;
clrscr();
void swap(int,int);
cout<<"num1="<<num1<<endl<<"num2="<<num2<<endl;
swap(num1,num2);
getch();
}
void swap(int x,int y)
{
int temp=x;
x=y;
y=temp;
cout<<"After swaping value is x="<<x<<" and "<<"y="<<y;
}
 Output of this program
num1=10
num2=20
After swaping value is x=20 and y=10
  • Pass by address and pass by pointer :- Pass by address is also another technique used for argument passing.In this technique as compare to pass value.We pass the address of actual argument to the formal argument that act like a pointer variable.In this any change made in formal argument are refer back to actual argument.                                                                                                         Program using Pass by address technique swap two number                                                                                                                                                                                         #include<iostream.h>
    #include<conio.h>
    main()
    {
    int num1=10,num2=20;
    clrscr();
    void swap(int *,int *);
    cout<<"Num1="<<num1<<endl<<"Num2="<<num2<<endl;
    swap(&num1,&num2);
    cout<<"After swaping num1="<<num1<<" and "<<"num2="<<num2;
    getch();
    }
    void swap(int *x,int *y)
    {
    int temp=*x;
    *x=*y;
    *y=temp;
    cout<<"After swaping x="<<*x<<" and "<<"y="<<*y<<endl;
    } Output of this program Num1=10 Num2=20 After swaping x=20 and y=10 After swaping num1=20 and num2 10 
  • Pass by reference :-The pass by reference is a very easy and simple technique of argument passing which is only available in C++. Using this technique,any modifications in the formal arguments(s) in the called function are reflected back to the actual argument(s) in the calling function.This method of argument passing which allows the modifications back to the actual arguments(s) is similar to the pass by address technique of argument passing but without using the complex syntax of pointers.Before discussing the concept of argument passing by reference.
Program using Pass by reference technique swap two number
#include<iostream.h>
#include<conio.h>
main()
{
int num1=10,num2=20;
clrscr();
cout<<"num1="<<num1<<endl<<"num2="<<num2<<endl;
void swap(int &,int &);
swap(num1,num2);
cout<<"After swaping num1="<<num1<<" and "<<"num2="<<num2;
getch();
}
void swap(int &x,int &y)
{
int temp=x;
x=y;
y=temp;
cout<<"After swaping x="<<x<<" and "<<"y="<<y<<endl;
}          

  Output of this program
num1=10
num2=20
After swaping x=20 and y=10
After swaping num1=20 and num2=10
 






.