Friday, March 11, 2016

C++ Tutorial

Friday, March 11, 2016 Posted by Sandeep Kumar Jha

C++ is a middle-level programming language developed by Bjarne Stroustrup starting in 1979 at Bell Labs. C++ runs on a variety of platforms, such as Windows, Mac OS, and the various versions of UNIX.

Object-Oriented Programming

C++ fully supports object-oriented programming, including the four pillars of object-oriented development:

  • Encapsulation

  • Data hiding

  • Inheritance

  • Polymorphism

When we consider a C++ program, it can be defined as a collection of objects that communicate via invoking each other's methods. Let us now briefly look into what do class, object, methods and Instance variables mean.

  • Object - Objects have states and behaviors. Example: A dog has states - color, name, breed as well as behaviors - wagging, barking, eating. An object is an instance of a class.

  • Class - A class can be defined as a template/blueprint that describes the behaviors/states that object of its type support.

  • Methods - A method is basically a behavior. A class can contain many methods. It is in methods where the logics are written, data is manipulated and all the actions are executed.

  • Instance Variables - Each object has its unique set of instance variables. An object's state is created by the values assigned to these instance variables.


C++ Program Structure:

#include <iostream>

using namespace std;


// main() is where program execution begins.
int main()
{
   cout << "Welcome Sandeep"; // prints Hello World
   return 0;
}

Let us look various parts of the above program:


  • The C++ language defines several headers, which contain information that is either necessary or useful to your program. For this program, the header <iostream> is needed.
  • The line using namespace std; tells the compiler to use the std namespace. Namespaces are a relatively recent addition to C++.
  • The next line // main() is where program execution begins. is a single-line comment available in C++. Single-line comments begin with // and stop at the end of the line.
  • The line int main() is the main function where program execution begins.
  • The next line cout << "This is my first C++ program."; causes the message "This is my first C++ program" to be displayed on the screen.
  • The next line return 0; terminates main( )function and causes it to return the value 0 to the calling process.


C++  Data Types

The following table shows the variable type, how much memory it takes to store the value in memory, and what is maximum and minimum value which can be stored in such type of variables.

Type
Typical Bit Width
Typical Range
char
1byte
-127 to 127 or 0 to 255
unsigned char
1byte
0 to 255
signed char
1byte
-127 to 127
int
4bytes
-2147483648 to 2147483647
unsigned int
4bytes
0 to 4294967295
signed int
4bytes
-2147483648 to 2147483647
short int
2bytes
-32768 to 32767
unsigned short int
Range
0 to 65,535
signed short int
Range
-32768 to 32767
long int
4bytes
-2,147,483,648 to 2,147,483,647
signed long int
4bytes
same as long int
unsigned long int
4bytes
0 to 4,294,967,295
float
4bytes
+/- 3.4e +/- 38 (~7 digits)
double
8bytes
+/- 1.7e +/- 308 (~15 digits)
long double
8bytes
+/- 1.7e +/- 308 (~15 digits)
wchar_t
2 or 4 bytes
1 wide character

C++  Keywords

The following list shows the reserved words in C++. These reserved words may not be used as constant or variable or any other identifier names.

asm
else
new
this
auto
enum
operator
throw
bool
explicit
private
true
break
export
protected
try
case
extern
public
typedef
catch
false
register
typeid
char
float
reinterpret_cast
typename
class
for
return
union
const
friend
short
unsigned
const_cast
goto
signed
using
continue
if
sizeof
virtual
default
inline
static
void
delete
int
static_cast
volatile
do
long
struct
wchar_t
double
mutable
switch
while
dynamic_cast
namespace
template


Variable

A variable provides us with named storage that our programs can manipulate.

DataType variableName1, variableName2,…variableNameN;

int i;      // declared but not initialised
char c;
int i, j, k;  // Multiple declaration


int i=10;         //initialization and declaration in same step
int i=10, j=11;

If a variable is declared and not initialized by default it will hold a garbage value. Also, if a variable is once declared and if try to declare it again, we will get a compile time error.



Loop

A loop statement allows us to execute a statement or group of statements multiple times and following is the general from of a loop statement in most of the programming languages.

There are 3 type of loops in C++ language


For loop



For loop is used to execute a set of statement repeatedly until a particular condition is satisfied. we can say it an open ended loop. General format is,


for(initialization; condition ; increment/decrement)

{

  statement-block;

}


Example




while loop

while loop can be address as an entry control loop. It is completed in 3 steps.

Variable initialization.( e.g int x=0; )

condition( e.g while( x<=10) )

Variable increment or decrement ( x++ or x-- or x=x+2 )



Syntax 

variable initialization ;

while (condition)

{

 statements ;

 variable increment or decrement ; 

}


Example





do while loop



In some situations it is necessary to execute body of the loop before testing the condition. Such situations can be handled with the help of do-while loop. do statement evaluates the body of the loop first and at the end, the condition is checked using while statement.



General format of do-while loop is,


do

{

 ....

 .....

}

while(condition)

Example





Nested for loop



We can also have nested for loop, i.e one for loop inside another for loop. Basic syntax is,

for(initialization; condition; increment/decrement)

{

  for(initialization; condition; increment/decrement)

     {

        statement ;

     }

}

Example


The Infinite Loop

A loop becomes infinite loop if a condition never becomes false. 
C++ programmers more commonly use the for(;;) construct to signify an infinite loop.

#include <iostream>
using namespace std;

int main ()
{
for( ; ; )
   {
      printf("This loop will run forever.\n");
   }
return 0;
}



Decision making in C++

Decision making is about deciding the order of execution of statements based on certain conditions or repeat a group of statements until certain specified conditions are met. C++ handles decision-making by supporting the following statements,

Simple if statement

The general form of a simple if statement is,

if( expression )
{
 statement-inside;
}
 statement-outside;


If the expression is true, then 'statement-inside' it will be executed, otherwise 'statement-inside' is skipped and only 'statement-outside' is executed.

Example





if...else statement

The general form of a simple if...else statement is,

if( expression )
{
 statement-block1;
}
else
{
 statement-block2;
}


If the 'expression' is true, the 'statement-block1' is executed, else 'statement-block1' is skipped and 'statement-block2' is executed.

Example




Nested if....else statement

The general form of a nested if...else statement is,

if( expression )
{
  if( expression1 )
   {
     statement-block1;
   }
  else
   {
     statement-block 2;
   }
}
else
{
 statement-block 3;
}


Example






Functions in C++

Functions are used to provide modularity to a program. Creating an application using function makes it easier to understand, edit, check errors etc.

Syntax of Function

return-type function-name (parameters)

{
// function-body
}
  • return-type : suggests what the function will return. It can be int, char, some pointer or even a class object. There can be functions which does not return anything, they are mentioned with void.
  • Function Name : is the name of the function, using the function name it is called.
  • Parameters : are variables to hold values of arguments passed while function is called. A function may or may not contain parameter list.
  • Function body : is he part where the code statements are written.

Call by Value

In this calling technique we pass the values of arguments which are stored or copied into the formal parameters of functions. Hence, the original values are unchanged only the parameters inside function changes.

Call by Reference

In this we pass the address of the variable as arguments. In this case the formal parameter can be taken as a reference or a pointer, in both the case they will change the values of the original variable.

Example




Array

C++ provides a data structure, the array, which stores a fixed-size sequential collection of elements of the same type.

An array is a sequence of variable that can store value of one particular data type.

type array_name[size];

int age[5];

This array can hold 5 integer elements.




Example






C++ Class

A class is the collection of related data and function under a single name. A C++ program can have any number of classes.

Class is defined in C++ programming using keyword class followed by identifier(name of class). Body of class is defined inside curly brackets an terminated by semicolon at the end in similar way as structure.

class class_name
   {
   // some data
   // some functions
   };

C++ Object

When class is defined, only specification for the object is defined. Object has same relationship to class as variable has with the data type. Objects can be defined in similary way as structure is defined.

class_name variable name;

temp obj1,obj2;



Accessing Data Members and Member functions

Data members and member functions can be accessed in similar way the member of structure is accessed using member operator(.).

For the class and object defined above, func1() for object obj2 can be called using code:

obj2.func1();

Similary, the data member can be accessed as:

object_name.data_memeber;

Constructor

Constructors are the special type of member function that initialises the object automatically when it is created .

Constructor has same name as that of class and it does not have any return type.

class A
{
 int x;
 public:
 A();  //Constructor
};

Destructor
Destructor is a special class function which destroys the object as soon as the scope of object ends. The destructor is called automatically by the compiler when the object goes out of scope.
The syntax for destructor is same as that for the constructor, the class name is used for the name of destructor, with a tilde ~ sign as prefix to it.
class A
{
 public:
 ~A();
};

Example


File Handling in C++

File Handling concept in C++ language is used for store a data permanently in computer. Using file handling we can store our data in Secondary memory (Hard disk).
Why use File Handling

  • For permanet storage.
  • The transfer of input - data or output - data from one computer to another can be easily done by using files.
  • For read and write from a file you need another standard C++ library called fstream, which defines three new data types:

Datatype
Description
ofstream
This is used to create a file and write data on files
ifstream
This is used to read data from files
fstream
This is used to both read and write data from/to files

Defining and Opening a File
The function open() can be used to open multiple files that use the same stream object.

file-stream-class   stream-object;
stream-object.open("filename");

Closing a File

A file must be close after completion of all operation related to file. For closing file we needclose() function.

outfile.close();

 put() and get() function

The function put() write a single character to the associated stream. Similarly, the function get() reads a single character from the associated stream.
read() and write() function
These function take two arguments. The first is the address of the variable V , and the second is the length of that variable in bytes. The address of variable must be cast to type char * (i.e pointer to character type).


file . read ((char *)&V , sizeof (V));
file . Write ((
char *)&V , sizeof (V));

Menu parser in C++