Thursday 19 March 2015

C++ Basic Tutorial

Introduction to C++

Object orientation and Object Oriented programming languages are playing an increasingly important role in the computing industry. With the gradual decline in hardware costs.  The cost of computing systems is largely dominated by software.  More tools that are powerful, operating systems and programming languages are evolving to keep up with the pace of hardware development.  Software for different applications needs to be developed under these environments, which is a complex process.  As a result, the relative cost of software (both   development and maintenance) is increasing substantially when compared to the cost of the hardware of a computing system.  Software maintenance is the process of modifying or extending the capabilities of the existing software.  It requires mastery over the understanding and modifying the existing software, and finally revalidating the modified software.

Beginning with C ++

C++ is an Object oriented programming language.  Initially named 'C with classes',  C++  was developed by Bjarne  Stroustrup at  AT&T Bell Laboratories in the early eighties.  The features of C++ were a combination of the object oriented features of a language called Simula 67 and the power and elegance of of C.  Therefore, C++  is an extension of C with a major addition of the class construct features of simula 67.


Some of the most important features that C++ adds on to Care classes, function overloading, and operator overloading.  These features enable developers to create abstract classes, inherit properties from existing classes and support polymorphism.

C++ is a versatile language for handing very large programs.  It is suitable for virtually any programmi8ng task including development of editors, compilers, database, communication systems and any complex real-life application systems.

The First C++ program


Let us begin with a simple program that  prints the string "Hello World" on the screen.

Example 1.1

#include
void main ( )
{
            cout << "Hello world;//c++ statement.
}


The Output operator

The only statement  in the above example is the Out[it statement.  The statement

            cout < < "Hello world",
Causes the string "Hello world" to be displayed  on the screen.  This statement introduces two features specific to C++ cout and <<. The identifier cout (pronounced as "see out")  is a predefined object that represents the standard output stream in c++. A stream is an abstraction that refers to a flow of data. Here, the standard output stream or device represents the screen.  It is also possible to redirect the output to other output devices.

The lostream.h File

The #include directive
            # include
Causes the contents of the file iostream. j to be added to the program in which it is included. It contains declarations for the identifier cout and the operator <<.This header file must be included at the beginning of all programs that use input/output statements.


Input using cin

Like cout. the identifier cin (pronounced as "see in") is a predefined object that corresponds to the standard input stream.  which in this case represents the keyboard.  the following program illustrates the usage of cin:

Example 1.2

// this program demonstrates the usage of the cin operator
''this program takes a string as input and displays it
#include
void main ( )
{
            char string [50]:
cout<<"Enter the string to be displayed/n"://prompts for input
cin >> string                                                    // takes input
cout <<"\n"<
}

Data Types

The need for data types is quite obvious to anyone who is  familiar with at least one programming   language.  Data types allow a programmer to create variables for manipulating data in programs.  The power of a programming language is often measured  by the variety and abundance of data types that it supports.

Data types in c++ can be classified under various categories-fundamental and user-defined.  The fundamental data types are those at the lowest level.  that is, those that are used for actual representation in memory.  The fundamental data types and their functions are listed in the following table.


Data type
Used for representing
Char (occupies 1 byte)
Characters and strings
int (occupies 4 bytes)
Integers
float (occupies 4 bytes)
Floating point numbers
bool
True or false values


Variables

A variable is a named location in memory that is used to hold a value that may be modified by the program.  All variables must be declared before they can be used.

Variables are fundamental to any language. Values can be assigned to  variables, which can be changed in the course of program execution.  The value assigned to a variable is placed in the memory allocated to that variable.  Variables can be created of fundamental as well as  user-defined data types.

Character variables
Are  used to store characters like ‘a’, ‘C’, ‘k’ and so on.
Integer variables
Are used to store whole numbers.
Float variables
Are used to store floating  point numbers.
Boolean variables
Can have one of two values-true of false. A bool is used to express results of logical operations.


Declaration of Variables


A declaration is a statement that introduces a variable into the program.  It specifies a type for that variable.  A type defines and ensures the proper use of the variable.



Operators and programming Constructs

A variable, when declared of a particular type. determines the set of legal operations that be performed on it.


Arithmetic operators

The binary arithmetic operators are +,-,*, /, and the modulus operator %
'+'        -           adds  two numeric values.
'-'         -           subtracts  the second value from the first.
'*'         -           multiplies two numeric values.     
'/'          -           divides the second value from the first.
'%'       -           divides the second value from the first and returns the remainder.


Relational Operators

The relational operators are
>          >=        <          <=        ==        !=

The operators compare tow values and return the appropriate result.


Logical Operators

The logical operators
&& and II
evaluate two expressions, and evaluation stops as soon as the truth or falsehood of the result is known.

Unary operators

The unary operators operate on one operand-variable or constant. C++ provides the two unary operators
++and --

Assignment Operators
Expressions such as
            n=n+2;
in which the variable on the left is immediately repeated on the right, can be written in a compressed from
            n +=2;
The operator +=is called the assignment operator.  Most binary have a corresponding assignment operator associated with them.

Programming Constructs

Switch ..case statement


C++ has built-in multiple branch selection statement called switch.  This statement successively tests the value of an expression against a list of constants.  When a match is found, the statements associated with that condition (constant) are executed. Consider the following example.


Example 1.3
//this program illustrates a switch., case construct #include
void  main ()

{
            char I;
            cout<<”\nEenter a rainbow color VIBGYOR”;
            cin>>I;
            switch(I)
{
                        case ’v’;          cout << “\nViolet”;
                                                break;
                        case ’I’;           cout<<”\nIndigo”;
                                                break;
                        case’ B’:         cout <<”nBlue”;
                                                break;
                        case ‘G’;         cout <<’\nGreen”;
                        case ‘Y’:         cout << “=nYellow”;
                                                break;
                        case ‘O’:         cout << “\nOranges”;
                                                break;
                        default ;          cout <<\nYou have entered the wrong
                                       colour”;
            }
}


The break statement in the above example causes an exit from the switch body.  It causes control to be  passed to the statement following the end of the switch construct., which in this case, is the end of the program.
The default keyword in the above program provides a way to take action if the switch variable does not match any of the conditions specified in the switch construct.

Conditional construct


C++ allows execution of a statement or a set of statements based on given condition. Consider the following statements.

If x>y
{
            cout<<”xis grater than y”;

}
else
{
            cout <<”y is grater than x”;
}
In the above code snippet, the statement “x is grater than y” is printed on the screen if the test expression is true, and the statement “y is grater than x” is  printted if the test expression is false.
The above code can also be written using the conditional ternary operator as
(x>y) ? cout << “x is grater than y”: cout << “y is grater than x”:

Looping Constructs

A loop. Causes a section of the program to be repeated a certain number of times.  The repetitiiion (or iteration) continues as long as the loop condition is true.  When the condition becomes false, the looping ends and control passed to the statement following the loop.
do. While loop

This construct executes the body  of the loop exactly once, and then evaluates the test condition. If the loop condition is true, the execution  is repeated otherwise  the loop ends and control is passed to the statement following the loop. The following example illustrates the usage of a do. While   loop.

Example 1.4


//this program illustrates the usage of of a do.. while loop
//this program accepts a character and returns its ascii value void main ( )
{

            char somechar, reply;
            int   asc_val;
            do
            {
                        cout << “\nEnter an alphabet’;
                        cin>>somechar;
                        asc_val=someschar;                       //assigning a character
                                                                                    //to an integer stores
                                                                                    //its ascil value
                        cout<<”/nThe ascil value of “<
                        cout<
                        cout<<”\nDoyou want to input another alphabat?”;
                        cin>>reply:
                        }while(reply==’’y’ IIreply ==’y’);
            }
while loop

The do.. While construct executes the loop once and then evaluates, whereas the while loop evaluates the condition first, and execution starts only if the condition is found to be true.To illustrate this, the above example has been rewritten using the while loop.


//this program illustrates the usage of the while loop
//this program accepts a character and returns its ascil valus
#include
void main ( )
{
            char somechar, replay=’y’;
int asc_val;
while (reply==’y’I replay ==’y’)
{
            cout <<”\nEnter an alphabat”;
            cin >>somechar
            asc-val=somechar;
            cout <<”\nThe ascil value of “<
            cout << asc val;
            cout<<”\nno you want to input another alphabat?”;
            cin>>reply;
}
}

for loop

The while and do..while loops are used when the number of iterations (that is, the number  of times the body of the loop is executed) is not known. When the number of iterations known, a or loop is used.  The following illustrates the use of the for loop.






Examples 1.6


//this program illustrates the usage of of a for loop
//this program prints the ascill values of all alphabets, one by one
#include
{
            char somechar=’a’;
            int asc_val,x=o;
            for (‘x26;x++)
            {
                        asc_val=somechar;
                        cout<<\nThe ascii value of “<
                        cout << asc_val;
                        somechar++;
            }
}


Arrays pointers and Functions


About this Chapter: This chapter gives a brief introduction to arrays and the fundamentals of array manipulation, explains about pointers and then proceeds to discuss function in detail.

Introduction


In everyday life similar objects are commonly grouped into units.  It would always benefit us to buy tables by the whole strip or bottle instead of buying one at a time. Similarly, in computer languages also we need to group objects of the same type, In C++ the mechanism   that enables this is the array.

Introduction to Arrays


An array is collection of elements of the same type that can be referenced  either individually or together-as a single module by a common name.  Each element of an array can be referred to by the- array name  and a subscript or index.

Defining Arrays


Like all other variables in C++, arrays must be defined before they can be used.  And like other definitions, an array definition specifies a variable type and a name.   But it includes another feature, a size.  The size specifies how many data items the array will contain.  It immediately follows the name, and is surrounded by square  brackets.  In  example 2.1 the array arr1 was defined as follows:
            Int arr1[5];
Where int is the data type of the array, arr1 is the name of the array and 5 is the size of the array.


Example 2.2


//this program shows days from start of the year to dta specified 3include
void main ()
{
                        int month, no_of_days;
                        int days [12]= {31,28,30,31,30,31,31,30,31,30,31};
                        cout <<”\nEnter the month (1to12);”;
                        if (month>12)
                        {
                        cout << “\nInvalid month”;
                        return;
            }
                        cout <<’\nEnter the day (1to31):’;
                        CIN>>no_of _of days;

                        If(no..of..days>31)
            {

                        cout<<”\nIvalid date”;
                        return;
            }
            for(int j=0;j
            no-of-days+days[j];
            cout<<\nTctal days from start of the year io”<
}
The output of the program will be:

Enter the month (1to12):4
Enter the day (1to31):7
Total days from start of the year is “<

Once it gets the month and no_of_days values, the program cycles through a loop, adding values from the days array to the no_of_days variable, and arrives at the final number of days.


Two_dimensional Arrays


So far we have looked at single dimensional arrays, where a single variable specifies array elements. But arrays can have more dimensions.  A two dimensional array is a  grid containing rows and columns where each element can be accessed by specifying the row and column coordinates.  The general form of declaration of a two_dimensional arrays is:
           
            Datatype arrayname [no. of   rows] [no. of columns];
A typical example of a character two-dimensional array would be one holding the weekdays, the array definition would be
            Char weekday [7] [10]  ={


                                                            “Sunday”
                                                                        “Monday”
                                                                        “Tuesday
                                                                        “Wednesday”
                                                                        “Thursday”
                                                                        “Friday”
                                                            “Saturday”
                                                            };
Since there are seven strings and the longest of them, Wednesday, holds nine characters, the column subscript in the   declaration is given as 10.Remember, a string needs an additional byte to hold the string terminator, the ‘\0’.

A brief discussion on pointers


A pointer is a variable that holds the address of another variable.  The statement

                        Int*ptr;
declares a variable ptr which is a pointer that may point to (i.e.,hold the address of ) any variable of type int. The unary operator’*’makes all the difference between an ordinary variable and a pointer type variable.  This operator, also called the indirection or dereferencing operator, when used in declaration, indicates that the variable is a pointer variable.  It is also used to get the value of whatever ptr is pointing to.  In a pointer declaration, the variable must always be preceded by an asterisk (‘*’) symbol.








Initialization of pointers


It is always good practice to initialize pointers as soon as they are declared. Initializing a pointer involves the assigning of the address of a variable to the pointer. In order to make a pointer hold the address of a variable, say x, the statements

            Int x;
            Ptr=&x;
Must be used.  Here, the operator ‘&”or the address operator returns the address of the variable x and assigns it to ptr. A pointer can be initialized even when it is declared.  For example, the declaration,
            Int x;
            Int*ptr=&x;

Is perfectly valid.

Functions

A function is a single comprehensive unit that performs a specified task.  This specified task is repeated each time the function is called.  Functions break large computing tasks into smaller ones.  They work together to accomplish the goal of the whole program.  Moreover functions increase the modularity of the program and reduce code redundancy.

Every  program must contain  one function named main where the program always begins execution.  The main function may call other function  which in turn, may again call still other functions.  When a function is called, the control is transferred to  the first statement in the called function.  The statement following the function call, or the expression begin evaluated with the function, is put into a stack.  After the function is executed, control returns to the calling function, and execution continues with the evaluation of the expression (retrieved from the stack)in which the cal was made.  A value can be returned when a function completes the specified task and that value can be used as an operand in an expression.

Functions can communicate data between themselves in two ways. One through global variables and the other through an argument or parameter list.

Function definition

A function definition introduces a new use-defined function to the program by declaring the type of value it returns  and its parameters, and specifying the statements that are executed when the function  is called.  Consider the following example.

Example 2.3

// this program illustrates the definition and usage of a function
//this program defines a function to take two numbers as input, add them and
//return  the result

3include
void  main ()  //every program must start with the main ( ) function, this is
                                    //where execution starts
{          
            int x, y, z;
            int add (intx,int y);
            cout << “\nEnter a number:”;
            cin >> x;
            cout <<”\nEnter another number:”;
            cin>>y:
            z=add(x,t);                                                      //the value returned by the
                                                                                    //function is  assigned to the
                                                                                    //variablez
            cout <<”n\The resutl is:”<
}

int add(intx,int y)
(
            return x+y;                                                     //the function add returns the
                                                                                    //sum of the two variables x,
                                                                                    //and y
}

The function in which the function call is contained is known as the calling function (which in this case is main) and the function named in the call is said to be the called function (here, it is add).  The function add () returns an integer value, which is assigned to a variable in main z, when a function is required to return a value, the return type has to be specified explicitly.   The general form of a C++ function is given below.


Example 2.4
            //call by value
            3include
            void main ( )
(
            int a=1, b=2;
            void swap (int,int);                            //functions must be
                                                                        //declared before they
                                                                        //can be used in a
                                                                        //program
            swap(a,b);
            cout <<”\na=” << a<<”b=”<
}

            void swap (int a,int b)
            {
                        int temp;
                        temp=a;
                        a=b;
                        b=temp;
            }
The output will be
A=1 and b=2 (The values of the variables are not exchanged)

//call by reference
#include
void main ()
{
            int a=1, b=2; 
            void swap (int *,int *);
            swap (&a,&b);
            cout << “na=” << “b=” <
}
void swap (int *a,int *b)
{
-
            int temp;
            temp =*a;
            *a=*b;
            *b= temp;
}
The output of the program will be
a=2 and b=1 (The values are exchanged)

Recursive functions


C++support  a feature  called recursion. A recursive function is a function that makes a call to itself.  Recursive functions can  be effectively used in  applications  in which the solution to a problem can be expressed in terms of successively applying the same solution  to subsets of the problem A useful example of recursion is the evaluation of the factorial of a given number.

Example 2.5

            // Function to display the factorial of numbers till 10

            #include
            void main( )
            {
                        int j;
            int factorial  (int);                                                      // function declaration
            for (j=0;<10 j="" o:p="">
                        cout <<’\n’ <
            }
           
            factorial (int n)
            {
                        int fact;
                        if(n==0)
                                    return 1;
                        else
                        {
                                    fact = n*factorail (n-1);
                                    return fact;
            }
}


Classes and objects


Introduction


In the first chapter, data types-both system and user-defined were discussed in detail.  Finally it was concluded that user-defined data types  can be defined using the typedef keyword. But creating a data type using the typed using the typedef keyword can be inadequate in most real life situations.  For example, a business application may find the storage and manipulation of dates quite a basic requirement.  In such a case typedef keyword would not help.

C++ offers programmers the capability to define customized user_defined data types (like the date)with the help of the struct declaration.  The declaration could be like.


            Struct date {
            Int dd;
                                    Int mm;
                                    Int yy;
                        };

Here, the biggest drawback in declaring a type like this is the weak ties it would have with its validations and related operations.  For example, in the case of the data type int, the user cannot enter characters other than numerical ones.  The compiler would not allow him to do so.  This is because the validations for this data type have been tied to it at the time of coding itself, C++ provides a simple and elegant means of ensuring this _include the validations as part of the date declaration itself.  This could  be done by using the class Construct.

Introduction to Classes and Objects


A class declaration in C++ is largely similar to a struct declaration.  Shown below is the class declaration for the data type date.

            Class date   {
                                                Int dd;
                                    Int mm’
                                                Int yy;
                                    };

Notice that the keyword struct  has been replaced   by the keyword class.  However, this definition is not complete.  The main idea behind using class is the binding of data along with its functionality.  The modified declaration of the data class, along with a validation function would look  like this.

            class date  {
                                    int dd;
                                    int mm;
                                    int yy;
                                    void valid(int d,int m)
                                    {
                                   
                                                if {d>31)
                                                            cout <<”nDate not valid “;
                                                if {m>12)
                                                            cout<
                                    }
            };

The function ‘valid’ is  now a member of the date  type. Such functions are referred to as  member functions or methods.  The data  members within the class_dd, mm, yy_are in
turn called member data.

Data Abstraction

Data abstraction is ability to create user-defined data types for modeling real world objects using built-in data types and a set of permitted operators.  The construct that helps create such data types and implement data abstraction in C++ is the class.  I helps in the creation and usage of user-defined or Abstract Data Types.

Encapsulation

Encapsulation  or data hiding is the mechanism that associates the code and the data  that it manipulates into a single unit and keeps them safe from external interference and misuse.  The class feature of C++ implements the concept of encapsulation by providing access specifiers.  Access specifiers control the visibility   status of the members of a class.  There are three access specifiers in C++_private,  public and protected.  The members of a class declared private are accessible only within the  class, I,e., only to other members of  the same class. The members declared are public as accessible anywhere from within the class,  or outside the class.  The protected access specifier will be discussed in detail in the next chapter.  The following example illustrates the usage of private and public access specifers.
            Class date {
                        Private:
                                    Int dd;
                                    Int mm;
            int yy;
public;
            void valid (int d, int m)        
            (
                        if (d>31)
                                    cout  <<”\nIvalid date”;
                        if (m>12)
                                    cout <<”\nInvalid month”;
            }
};

Dynamic Memory Manipulation

C++ provides two special operators to perform memory management dynamically. They are the new operator for dynamic memory allocation and the delete operator for dynamic memory deallocation.  These operators offer dynamic memory management similar to the library functions malloc () and free()

The new  opertor

The general format of the new operator is as follows:

            DataType “new Datatype {size in integer};

Where datatype is the return type, the pointer to that type which will be returned; new is the new operator, datatype is again the type for which memory is to be allocated and size is the number of items to be allocated (this is optional).The statement.
            date*date;
            date1=new date;
allocates memory for an integer  and returns a pointer of type int, which is assigned to int_ptr. This statement is similar to the C statement.

            Date1=(date*)malloc(size of(date));

The delete operator

The counterpart of the new operator, delete, ensures the safe and efficient use of memory.  This operator is used to free the block of memory allocated by the new operator. Although the memory allocated is returned to the system when the program terminates, it is safer to explicitly free memory using the delete  operator.  The format of this operator is
            delete pointer variable;
where pointervariable is the pointer returned through the new operator.  The c++ statement

            delete datel;

for deleting the object date is equivalent to the C statement

free (datel);


Constructors and Destructors
All built-in data types, with respect to variables with the exception of  pointers, offer some from of initialization and cleanup.  When a variable is declared. Memory  is automatically set aside for it, and when the variable goes out of scope, the memory allocated for it is released.  In order to simulate this, C++ provides two features calledconat constructors and destructors.

Constructors
A constructor is basically a function used for initialization-to initialize variables, to allocate memory, and so on. Take the date class for  example. Assume that each time an object of the date class is created, it is to be initialized with the date 01/01/1970.The data within the class (any class)cannot be initialized at the time of declaration.  this is because the declaration of a class serves only as a template, and no memory is allocated at the time of declaration. This problem can be solved by writing an initialization fuction-aconstructor.

Example
//this program illustrates the usage of a constructor
//this program initializes a date class object with the date_
//01/01/1970
#include

class date
{
            privates;
                       
                        int dd;
                        int mm;
                        int yy
public;
                       
                        date()
                        {

                                    dd=01;
                                    mm=01;
                                    yy=1970;
                       
                        }
                        void display ()
                        {
                        cout<<”/n”<
                        }
void main ()
{
            date date1;
            date1.display();
}

Example
//this program illustrates the usage of a constructor
// this program initializes a date class object with a date specified
// by the user

#includes

class date

{
private;

int dd;
int mm;
int yy;
public;
date (int d,inr m, int y) //constructor that takes //parameters
            {
                        dd=d;
                        mm=m;
                        yy=y;
            }
            void display ()
            {
                                    cout <<”/n”<
                        }
};

void main()
            date date1 (1,1,1998);        
            datel. display();
}


Destructors

Constructors serve to automatically initialize variables, data members at the point of creation. Destructors are complimentary to constructors. They serve to de-initialize objects when they are destroyed.

A distracter may be called either when the object goes out of scope or when it is destroyed explicitly using the delete operator.  A   destructor, like a constructor has the same name as that of the class.  But is prefixed by the tilde (“-“)symbol. A class cannot have more than one destructor. And a  destructor cannot take arguments or specify a return value.  Consider the declaration of a word class as given below.

            Class word    {
                       
            Private;

            Char *str_word;
           
            Public;
           
            Word(char*a);
            {
                        str-word=new char(strlon (a)];
                        strcpy(str-word,s);
            }
            int getlen ()
            {
                        return strlen(str_word);       
            }
            char*getword()
            {
                        return str_word;
            }
            -word()
            {
                        delete str_word;
            }
                                    };

Copy constructors

There may arise a situation where class constructors are not invoked to initialize a newly defined class object.  This is when one objects is used to initialize another using the assignment operator.
Class word    {
                                    Private;

                                    Char *str_word;
                                   
                                    Public;
                                   
                                    Owrd(char*s)
                                    {
                                                str_word=new char[strien (s)];
                                                stropy(str_word,s);

                                    }
                                    int getlen ()
                                    {
                                                return str\-word;
                                    }
                                    -word()
                                    {
                                                delete str_word;
                                    }
                        };

The scope operator

Assume that in a huge class with a lot of  members data and methods, the members functions are defined within the class definition itself. This may make the class definition messy and unreadable.  The scope (“: :”) resolution operator separates the body of the function from the body of the class.  Using the scope operator, the programmer can define a  member functio outside the class definition, without the function losing its connections with the clas itself.

Class word    {
                                    Private;
                                   
                                    Char *str_word;
                                   
                                    Public;
                                   
                                    Word(char*s);
                                    Int getlen ();
                                    Char *getword ();
                                    -word ();
                       
                        };
                        word;word(char*a)
           
                        {
                                    str.word=new char (strlen (s)];
                                    strcpy (str-Word,s);
                        }
                        int word; getlen ()
                        {
                                    return strlen (str_word);

                        }
                        char*word::getword()
                        }
                                    return str_word;
                        }
                        owrd::-word()
                        {
                        delete str_word;
                        }

The ‘this’ pointer

 If every instance of a clas carries a copy of the member functions within it, it would be a considerable overhead on system memory, especially if the functions happen to be lengthy.  As an alternative, each object holds its own copy of the dat members alone, and a pointer to a list of methods of the class.  Only one copy of the member functions exists in memory.

                        Char* word ::getword()
                        {
                                    return this ->str_word;
                        }
                       
                        word:: word (char*str_word)                       //the variable and
                                                                                                //member data have the
                                                                                                //same name, invoking
                                                                                                //confusion

                        {
                                    this->str_word=new char [strlen (str-word];
                                    strcpy (this_>str_word,str,word);
                        }
Static variables and static functions

In the previous section, we had mentioned that objects of a class maintain their own copy of member data.  In some cases, it is imperative that all objects of a class have  access to the same copy of a single variable.  Take the word class for instance. Assume that the number of word existing at any given point of time i.e.,  the number of objects created for that class must available.

Example

 #include
#include
class word
{
            private:
                        char *sr_word:
static int wordcount; //a sttatic member keeps cont of the //number of
objects create  for     //this class
                                                public:



           
word (char*):
            int getlen (void);
            char *getword (void):
            void init (void):
            -word ( );
                                    {
                                                str_word+new char [strlen (s)];
                                                strcpy (str_word,s):
                                                wordcount=++wordcount;
                                                cout <<”nThe wordcount is “<
                                    }
int word::geten ()
{
            return strlen (str_word);
 };
  char*word::getword()
  {
            return str_word;
  }
   void word :: init ( )
 {
            wordcount =1;
 }
word::_word ()
                                    {
                                                delee str_word:
                                                wordcount+__wordcount;
                                    }
                                    void main (
{
                                                word word1(“This is a teat”);
word.intit(); //after the first object //is created, the word //count is initialized //to 1
word word 2 (//This is another teat”);
//wordcount is                        //incremented to2
                                                            word word3 (“This is the third test”):
//wordcount is 3
                                                }

Static Functions

Static  functions are member functions that access only the static data in a class.  For example, the init ()function in the word class discussed above accesses only the static member wordcount.  This  function can be declared as static.

Inheritance

Introduction

The basic philosophy behind Object Orientation is to represent things as they exist in the real world. For example, unlike the procedural programming languages, C++treats everything (well, almost everything) as objects. Like  objects exist in the real world, obects in C++ contain properties (data members) and behavioral attributes (methods). Similarly, another concept has been implemented in C++ based on the real world_inheritance.

What is Inheritance?

Inheritance is the concept by which the properties of one entity are available to another. It allows new classes to be built from older and less specialized classes instead of being rewritten from scratch.  Looking at the real life part of it, a child inherits his looks, mannerisms and qualities form his parents. In order to  simulate this environment, C++ allows a class to inherit properties and functions from another.  The class that inherits properties and functions  is called the subclass or the derived class and the class form which they are inherited is called the super class or the bass class.  The derived class inherits all the properties of the base class and can add properties and refinements of its own. The base class remains unchanged.
        Base class: A
                                   
Data one

Data two

Data three

Data four
 
                                               






 



                                   
Data five

Data six

Data seven
 
 




                                                           

                                                           



Derived class:B


In the above diagram. B inherits from A which consists of data members one. Two, three and four.  All these members are inherited by B. Apart this, B’s own data members include five, six and seven.

Class A
Class B
One, two three, four
One, two, three, four, five, six, seven


Any class can be a base class.  More than one class can be derived from a single base class and vice versa.  A derived class can also act as a base class for another class.

Assuming that class A already exists, the general format for inheriting class B form A is as follows:
            Class B: public A
            {
                        private:
                                   
                                      ---------
                          --------
                        public:
                                               
                                       ------
};
In the above declaration, the single (‘:’) is used to specify that the class being declared  is derived from another class (the name of which is specified after the colon). The keyword ‘public’ follows the colon, and it is an access qualifier used to specify what kind of an inheritance it is. If it is a public inheritance, it means that the public members of the base class are brought into the derived class as public members.

Types of inheritance

As we mentioned earlier, the ‘public’ qualifier used when deriving one class from another, specifics that all public members of the base class become public members of the derived class.  All members of the base class are inherited as they are public as public and protected as protected.  All the access restrictions of members of the base class remain the same, whether they are accessed from the object of the base class or that of the derived class.

The ‘private’ qualifier

If the ‘private’ qualifier is used when deriving a class, all the public and protected members of the base class become private members of the derived class, I,e., the members  of the  base class can be accessed only within the derived class, they cannot be accessed through an object of the derived class. The private qualifier is rarely used. It is used to end a hierarchy of classes.


The “protected” qualifier

This qualifier, when used while deriving a class, specifies that all public and protected members of the base class must become protected members of the derived class.  This means that, like a private inheritance, these members cannot be accessed through objects of the derived class, whereas, unlike a private inheritance, they can still be inherited and accessed by subsequent derived classes.  In other words,protected inheritance does not end a hierarchy of classes, as private iheritance does.

The following table illustrates this.

Qualifier
Private
Protected
public
Private
Private*
Private
Private
Protected
Private*
Protected
Protected
Public
Private*
Protected
public


*These members cannot be accessed from within the derived class also

Note:
     Private members of the  base class are not accessible from within the derived class, whatever be the type of inheritance.  They just add to  the derived class member list and can be accessed only through the inherited public or protected members function of the base class.

Scope Resolution with Overridden members
The scope resolution (‘::”) operator_discussed in the previous chapter, can be used to access base class functions through an object of the derived class.  For example, to access the function activity of the parent class through a child class object, the statement to given is:

                  Child child_name;
                  Child_name.parent::activity ();
A base class function can be accessed from within the derived class by  the statement:
      Parent::activity ( );

Multiple Inheritances

So far we discussed classes deriving properties and function from a single base class. Classes can also have multiple ancestors or base classes. Consider an amphibian for example. It inherits properties from a land animal as well as from water animals.  The format for this would be:
           
            Class 1-animal
            {
                        ......
                        ......
            };
           
class w_animal
{
            ......
            ......
};

class amphibian: public  1_animal,public w_animal
{

            ........
            ......
};
In the above statements, all a class takes to derive from multiple base classes is a list of comma (‘,’)separated base  classes in the derived class declaration.  However, there are certain finer aspects in deriving form multiple base classes. Consider the declaration:
           
            Class amphibian:public 1_animal,w_anima1
            {
                        ......
                        ......
            };

Base Class Initialization

When a new class is derived from a base class, the constructors of the base class are not inherited.  Remember that the derived class includes all the data members of the base class.  When an object of the derived class is created, these members (of the base class) have to be initialized as well. Since the constructor is nor inherited, it has to be invoked explicitly from the derived class.  If a constructor is not explicitly invoked in the derived class, the compiler invokes the default constructor of the base class.

Consider the child class, inherited from parent. The derived class has to specifically invoke the base class constructor as shown below:
           
Child::child(char *c,char *p)
            :parent (char *p)
{
            c_name=new char [strlen (c)];
            strcpy (c_name,c);
}
The colon (‘:’) is used to invoke a base class constructor from the constructor of the derived class.  When an object of the derived class is created, the base class constructor is executed before that of the derived class.

Multipath Inheritance

With respect to the parent- child example discussed above, let us consider a more complex situation. Assume there are two child classes inheriting from the same parent class.  And a grandchild inherits from both child and child2. The inheritance is as given below.
Parent
 
 








     
 








           
Consider the code for this inheritance inheritance hierarchy as given below:
           
            Class parent
            {
           
                        private:
                        char p_name [20];
           
                        public;
           
                        parent (char*p)
                        {
                                    p-name=new char [strlen (p)];
                                    strcpy (p_name,p);

                        }
                        char *p_getname  ()
                        {
                                    return p_name;
                        }
class child:public parent
{
            private;

            char c_name [20];

            public;

            child (char*c1)
            {
                        c_name=new char [str1en (c1)];
                        strcpy (c-name, c1);
            }
            char *c1_getname ()
            {
                        return c_name;
            }
};
class child2;public parent
{
            private;

            char c_name [20];

            public:

            child2 (char*c2)
            {
                        c_name=new char [strlen (c2)];
                        strcpy (c_name, c2);
            }
            char *c2_getname ()
            {

                        return c_name;
            }
};

class grandchild:public child1,public child2
{
            private:

            char gc_name[20];
public:

grandchild(char*gc)
{
            gc_name=new char[strlen(gc)];
            strcpy (gc_name,gc);
}
char *go_getname()
{          
            return gc_name;
            }
};

Friend Functions

C++ provides another feature to improve the performance of programs_friend fucntions.
Consider the parent class discussed above. The declaration of the parent class is:
            Class parent
            {
                        private;

                        char p_name[20];

                        public :

                        parent (char*p;
                        {
                                    p_name=new char[strlen(p)];
                                    strcpy (p_name,p);
                        }
                        -parent()
                        }
                                    delete p-name;
                        }
};


Polymorphism

Introduction
           
The origin of the word polymorphism is simple.  It comes from the two Greek words poly (many and morphos (form)- multiform.   Function and  operator overloading are crucial elements in C++ programming. Not only do these two features provide most of the support for compile time polymorphism, they also and flexibility and extensibility to the language.  Function overloading is simply process of using the same name or two or more functions.  Although operator overloading is similar to function overloading, we need to know about function overloading before going in for operator overloading.

Overloading
In English some verbs are used in different contexts to express different actions.  Consider the word ‘patient’ whose meaning differs when used in different contexts.

¨            The doctor examined his patient.
¨           One must be patient and not be too hasty while taking decisions.

Function Overloading

Function overloading is just using the same name for two or more functions. Passing different types of parameters or different number of parameters to the function incorporates this. It can even be the sequence of parameters. It is only through this signature that the compiler decides which function to call in a given situation.

Example

#include

int FunctionName (int I);
double FunctionName (double I);

main ()
{
            cout <
            cout <
            return 0;

}

int FunctionName(int I)
{
            i+=10;
            cout<<”Inside int FunctionName (int I)”<
            return I;
}

double FunctionName (double I)
{
            i+=10.5;
            Cout <<”Inside double FunctionName(double I)”<
            return I;
}

The output of the program would be

Inside int FunctionName(int i)
20
Inside double FunctionName(double I)
20.83

Example

#include
class sample
{
private:
            int value;
public:
            void function(int v)
            {           v=value;         }
            int function()
{           return value; }
};

main()
{
                                                sample s;
                                                _s.function(7);
                                                int I=s.function();
                                                cout<<  i<
}
Scope resolution

It is possible to access function names redefined in a base class. Like the function fun()in the previous example. Functions defined in different unrelated classes are not considered overloaded, so explicit scope resolution is not always needed. The scope resolution operator (::)can either be used inside the member functions of any derived class, or at the time of the function call from the main program.

Example

#include

class A
{
public;
                                                int fun (int i)
{
                                                return i+1;
}
};
class B: public A
{
public:
                                    int fun (float f)
{
                                    return f+10;
                        }

                                    int  fun (int I)
{
                                    return A::fun (i);
                        }
};
void main ()
{
                                                B b;
                                                Int I= b.fun(2);
Int j =b.A::fun (2);
Float z =22/7;
Int k =b.fun (z);
cout <
cout<
cout <
cout<
}

Virtual functions

In C++, the function is declared as virtual to specify late binding. A virtual function is a function that is declared as virtual in a base class and redefined in the derived class. To declare a function as virtual, its declaration is preceded by the keyword virtual.

Example
           
            #include

            class Base

            {
            public:
                        virtual void Display ()
                        {
                        cout<<”This is the base class  virtual function “<
            }
}:
class Derived1 :public Base
{
public:

            void Display ()
            {
            cout<<”This is the Derived1 class display function “<
            }
};

class Derived2:public Base
{
public:
            void Display ()
            (
            cout <<”This is the derived 2 class display function “<
            }
};

void main ()
{
            Base *b;
            b=new Base;
b-Display(); //displays the base class display function
b=new Derived 1;
b->Display (): //dispalys the derived1 class display function
b=new Derived2:
b->Display(): //display the derved2 class display function.
}

Abstract classes

A class that contains at least one pure virtual functions is said to be an abstract class, because an abstract class contains one or more functions for which there are no definitions. No object of an abstract class is created. Instead, an abstract class constitutes an incomplete type that is used as a function for the derived class.


Example
           
#include

            class A{
            public:
            virtual void print ()=o;
            };

            void main ()
            }:

            void main ()
            {
            A *a:
            A= new A: //cannot create object of an abstract class. S
            a->print ():
            }
Abstract classes are set up for the benefit of derived classes. Abstract classes normally occur at the root of the hierarchy. There can be any number of abstract classes in the same hierarchy.
class A
virtual  void Function ()=0:
 
 


           
 



class B
virtual void Function():


 
           

           
           

class C
virtual void Function():

    
 
 







FILE HADLIG    

Introduction

The older versions of C++ had a smaller and different I/O class library.  The definition of the library was in the file stream. h. Most of the C++ compilers still support the older stream class for the sake of compatibility.  But it is advisable to use the modern I/O library, which is defined, in the iostream.h file.

Stream manipulation

The file handling techniques of C++ support file manipulation in the form of stream objects. The stream objects are predefined in the header file, iostream.h that is a part of the C++ language. There are no predefined objects for disk files.  All class declarations have to be done explicitly in the program.

Each stream is associated with a particular class, which contains member functions and  definitions for dealing with that particular kind of data flow.  There are three classes for handling files.

ifstream          -           for handling input files.
ofstream         -           for handling output files.
fstream           -           for handling files on which both input and output can be performed.          

The Stream class Hierarchy

An extensive use of some of these classes has been already made.  The extraction operator >>is a member of the istream class, and the insertion operator<

Advantages of C++ stream classes are:

§  The Stream classes form a powerful set of classes. They can be modified, extended or expanded to incorporate user-defined data types or classes.
§  They are fully buffered thus reducing disk access.
§  They offer a rich set of error-handling facilities.
§  They encapsulate their internal working form the user. The type of data to be input or output need not be specified by the programmer. The stream class automatically determines it.


File Input and Output

C++ also provides specific classes that deal with user-defined streams which are in the form of files.  To perform file I/O, the header file fstream.h must be include d in the program. It defines several classes.  including ifstream, of stream and fstream.

Opening and Closing a File

Before opening a file, a stream (input  output or input/output) be first obtained. To create an input stream, it must be declared as a class of ifstream.  To create an output stream, it must be declared as a class of ofstream. Sstreams that will be performing both input and output operations must be declared as a class of fstream.

ifstream in:                //input stream
ofstream out:             //output stream

fstream io:                  input and output stream

Here, filename is the name of the file, which may include a path specifer.  The value of mode determines how the file is opened.  It must be one (or more) of these values.

ios::app                      -appends to end of file.
ios::ate                       -seek to end file when file is opened.
ios::binary                  -open file in the binary mode.
ios::in                         -specifies that the file is capable of input.
ios::nocreate             -causes open( )function to fail if the file does not exist.
ios::norepace            -cause open() function to fail if file exists.
ios::out                       -specifies that the file s capable of output.
ios::trunc                    -causes the contents of a preexisting file by the same name be    destroyed.         

The value of access determines how the file can be accessed.  Its default value
is filebuf:: openprot, which specifies a normal file.  Other options like the file sharing options are typically specified using the access parameter in networked environments.

ofstream  out:
out.open("test",ios::out);

To open  a  stream for input and output, both the ios:;in and the ios::out mode values must be specified.  this can be done as follows.

fstream mystream:
mystream.open("test", ios::in  Iios::out):

To close a file, the member function close( ) must used. The close function takes no parameters and returns no value.

mystream.close():           


Reading and Writing Text Files

Reading from and writing to a text file is very easy.  The <>operators are used the same way the console I/O operations are performed, except that instead of using cin and cout, the stream that is linked to the file must be substituted.

Example

                      #            include
                      main
                      {
                      ofstream out ("ITEMS"):
                     
                      out<<"Shirts "<<625 end1:="" o:p="">
                      out<<"Jeans "<<760 o:p="" rnf1:="">
                      out<<"Trousers"<<600 en="" nbsp="" o:p="">
                     
                      out.close ():
                      ifstream in ("ITEMS"):
                     
                      char item [20]:
                      float cost:

                      in>>item>>cost:
                      cout<
                      in >>item>>cost:
                      cout<
                      in>>item>>cost:
                      cout<,item<<" "<
                      in.close( ):
                      return o:
                      }



read ( ) and write ( ) functions

The read ( ) and write ( ) functions are string oriented.  These functions are called with two parameters.  The read ( ) and write ( ) functions have the following syntax.

infile.read ( (char*) &variable, sizeof (variable)):

outfile. write ((char*) &variable, sizeof (variable)):

Example
                      #include
                      void main ( )
                      {
                                    int var1,n1:
                                    float var2, n2:
                                                       
                                    cout<<"Enter an integer value:"
                                    cin>>var1:
                                    cout<<"Enter a float value:"
                                    cin >>var2:

                                    ofstream out ("myfile", ios::binary):
                                    out.write ( (char*) &var1, sizeof (int) ):
                                    out.write ((char*) &var2, sizeof (float) ):
                                    out. close( ):

                                    ifstream in ("myfile", ios::binary):
                                    in. read ( (char*) &n1, sizeof (int));
                                    in read ( (char*) &n2,sizeof (float)):
                                    cout<
                                    cout<
                                    in.close( ):
                                    }

Peek ( )

The peek function obtains the next character from the input stream without removing it from that stream.  The syntax of the function is:

int peek ( ):

Flush( )

When data written into the output stream, it is not immediately written to the disk. Instead, the data is stored in an internal buffer.  When the buffer becomes full, the data written into the disk from the buffer. However, the data can be forced to be written into the disk before the buffer is full. This is done by calling the flush ( ) function. The   prototype of the functions is:

ostream &flush ( ):


igonre( )

Ignore function is used to read and discard characters from the input stream.
istream &ignore(int num,int delim)       


Templates

Introduction

In this chapter we go on discussing about the usage of templates such as function and class templates.  Templates are generic for any data types.  Later part of this chapter discusses about the exception handling.  The program can automatically invoke the user defined messages when the error occurs.

Templates
The normal meaning of the word "template "accurately reflects its use in C++. With a template, it is possible to create generic functions  and generic classes. In a generic function or class, the type of data upon which the function or class operates is specified as a parameter. Thus function or class with several different types of data without having to explicitly recode for different data types.

Generic Functions

A generic function defines set of operations that will be applied to various types of data.  A generic function has the type of data that it will operate upon passed to it as a parameter.  For example sorting can be applied to an array of integers or an array of floats. Hence creating a generic function helps to operate on any data types.

A generic function is created with the keyword template.  The general form of a template function definition is.

templateret_type Function(parameter list)
{
//body of the function
}



Example
#include

template void swap (T&a, T&b)
{
T temp:
temp=a:
a=b:
b= temp:
}

void main ()
{
int I=10,j=20:
float x=10.1,y=33.33:
char a=’N’, b=’A’:
cout <<”Original value of I and j is ‘<
cout <<”Original value of x and y is “<
cout << Original value of a and b is “<

swap(I,j);
swap (x,y):
swap (a,b):

cout <<”Swapped value of i and j is “<
cout <<”Swapped value of x and y is “<
cout <<”Swapped value of a and b is “<
}

the output of the program would be

Original value of I and j is        10           20
Original value of x and y is       10.1      33.33
Original value of a and b is       N          A
Swapped value of i and j is       20         10
Swapped value of x and y is    33.33    10.1
Swapped value of a and b is    A           N
Glossary
Abstract class
is a  class that has atleast one pure virtual function.
Access specifier
control the visibility status of the members of a class
Address  operator
returns the address of a variable.
Array
is a collection of elements of the same type.
Cin
pronounced as “see in”, is a predefined object that corresponds to the standard input stream.
Constructor
is basically a function used for initialization.
Constructor overloading
when an object of a class is created. the user can create different kinds of instances of the same class.
cout
pronounced as ”see out” is a predefined object that represents the standard output stream in C++
Declaration
is a statement that introduces a variable into the program.
Default constructor
is a constructor that does not take parameters.
Destructors
save to de-initialize objects when they are destroyed.
Elements
of an array are the items in the array
Encapsulation
or data hiding is the mechanism that associates the code and the data it manipulates into a single unit and keeps  them safe from external interference and misuse.
Friend function
is not a member of the class but it can access all public, protected and private members of that class.
Function
is a single comprehensive unit that performs a specified task.
Function overriding
is the member function of the base class being overridden in the derived class with some other activity, which hides the base class functionality.
Generic function
is a set of operations that can be applied to different datatypes.
Inheritance
is the concept by which the properties of one class are available to another.
Method
is a member function of a class.
Multiple inheritance
a class that is derived from more than one base class.
Operator overloading
is  that the scope of the operator is increased from normal operations to perform something else.
Operators
perform permitted operations on variables.
Polymorphism
is from the two Greek words poly (many) and morphos (form)-multiform_is the ability of an object to do more than one activity.
Public inheritance
is that the public members of the base class are brought into the derived class as public members.
Scope resolution
operator separates the body of the function from the body of the class.
Static binding
is the association of an object with a class at compilation time.
Static variable
is a variable that retains its value even after the block in which it is declared goes out of scope.
Stream objects
a technique in C++, which helps in file manipulation.
Subscript
or index is a single element of an array.
Template
is a  prototype_a function or class with different datatype.
this
 pointer contains the address of the object through which the function is begin invoked.
Variable
is a named location in memory that is used to hold a value that may be modified by the program.
Virtual function
is a function that is declared as virtual in a base class and redefined in the derived calss.


















                     








           

















                       














           







                       













     
           

























































































No comments:

Post a Comment

CakePHP Date Picker

Folder Structure: Controller:   File location - cakephp/src/controller/HomepageController.php namespace App\Controller; use...