Pages

Friday, August 26, 2011

Writing a file

Program to store data in a file using the redirection operator "<<"
#include<iostream.h>
#include<conio.h>
#include<fstream.h>
void main()
{
 ofstream out("data"); // creating a file in out(writing) mode.
 char name[20],addr[20];
 cout<<"\nName : ";
 cin>>name;
 cout<<"\nAddress : ";
 cin>>addr;
 out<<name<<"\n"<<addr; // sending the data to the file
cout<<"Data saved in the file";
out.close();
}


The above code  will create a new file named "data", if the file is already present it will be overwritten. The name and address entered by the user will be sent to the file using the "<<" operator. The message "Data Saved" will confirm the writing of the file.
To check whether the file has been created or not follow any of the following steps
1. Select "File--> DOS Shell".
In the DOS Shell, type the following command
type data
2. Search the "data" file using my computer and double click on it. When the "Open With" dialog box appears select "Notepad" and click OK.


Wednesday, August 24, 2011

File Modes

File Modes In C++


ModeDescription
ios::appIf FileName is a new file, data is written to it.
If FileName already exists and contains data, then it is opened, the compiler goes to the end of the file and adds the new data to it.
ios::ateIf FileName is a new file, data is written to it and subsequently added to the end of the file.
If FileName already exists and contains data, then it is opened and data is written in the current position.
ios::inIf FileName is a new file, then it gets created fine as an empty file.
If FileName already exists, then it is opened and its content is made available for processing
ios::outIf FileName is a new file, then it gets created fine as an empty file. Once/Since it gets created empty, you can write data to it.
If FileName already exists, then it is opened, its content is destroyed, and the file becomes as new. Therefore you can create new data to write to it. Then, if you save the file, which is the main purpose of this mode, the new content is saved it.*This operation is typically used when you want to save a file
ios::truncIf FileName already exists, its content is destroyed and the file becomes as new
ios::nocreateIf FileName is a new file, the operation fails because it cannot create a new file.
If FileName already exists, then it is opened and its content is made available for processing
ios::noreplace If FileName is a new file, then it gets created fine.
If FileName already exists and you try to open it, this operation would fail because it cannot create a file of the same name in the same location.

Sunday, August 21, 2011

Process of File Handling

Process Of File Handling

  1. Select Link/Stream Type : The first step in file handling is to determine what we want to "do" with the file - read,write or both. Once the "need" is known, we can select the appropriate "stream" to the desired operation. The following classes are can be used for various function.
    • Reading a file (From the file to memory) : Reading refers to the process of reading or traversing the data of a file either fully or partially. If we are searching the data in the file it will also be referred to as "reading". To read a file in C++, we must use the "ifstream" class.  It can be used in two modes, here is the syntax for both of them
      a) Using Constructor : ifstream in("filename")
      b) Using Open() Function :
      ifstream in;
      in.open("filename", ios::in);

      Note that with open(), a file mode(ios::in) is used. ios::in is the default mode for ifstream and can be removed also. For a complete list of file modes Click here
    • Writing a file (From the memory to file) : Writing refers to the process of storing data in a file. The data can be either static or can be asked from the user.The "ofstream" class is used to write data in the file. Like ifstream it too can be used in two modes,
      a) Using Constructor : ofstream in("filename")
      b) Using Open() Function :
      ofstream out;
      out.open("filename", out.write);
      Again the "out.write" mode is the default mode for "out".
    • Writing and Reading (From the memory to file and file to memory) : If we want to write and read the data from a file at the same time, then instead of first opening the file in "ofstream" and then in "ifstream", we can use the "fstream" class that can perform both "writing and reading" operations. This will save the time and memory that will be required where file are closed and reopened.
      fstream file;
      file.open("filename",ios::in | ios::out );
      Since fstream can perform both reading and writing tasks, it is compulsory to specify the modes to let the compiler know what kind of operation we want to perform.
  2.  Process the file as required :  Once the file is opened, the next step is the process the file as required. For example, if the program is for writing the data, then using the appropriate functions the data should be written or if the reading of the file is required then proper functions should be used to read the file.
  3. Close the file : After processing the file, it is better to close it so that the memory resources allocated to it are released. A file once closed, can be reopened anytime if required. To close a file the close() function is used.
    in.close();
    out.close();


Saturday, August 20, 2011

File Handling

File is a collection of data or bytes.  The collection can be in the form of  characters, words, lines, paragraphs and pages,fields,records, image, audio or video. The meaning attached to a particular file is determined entirely by the data structures and operations used by a program to process the file. It is conceivable (and it sometimes happens) that a graphics file will be read and displayed by a program designed to process textual data. The result is that no meaningful output occurs (probably) and this is to be expected. A file is simply a machine decipherable storage media where programs and data are stored for machine usage. It is used to store any information permanently on a secondary storage device such as a hard disc, floppy, CD/DVD or flash drive. We need to store data on a device because the data entered by the user or processed by the program is stored in RAM. Since RAM is a temporary memory, it will store the data only as long as the computer or the program is running. If you switch off the computer or close the program, all the data entered by the user will be lost and will have to entered again. Entering the data again and again is not only time consuming but also impractical since it does not make any sense to enter the data each time the program is run.
File Handling is the process of storing data in a file so that it can be used later. Using a file handling program we can,
  1. Create a file.
  2. Store data in the file.
  3. Read the data.
  4. Edit the data.
The main benefit of storing data in a disc file is that it is "permanent" and will store data till it is deleted by the user.

Streams : Stream is usually flow of a water body from one place to another. With reference to C++ file handling, a stream is used to move data from one location to another.Streams act as an interface between files and programs.They represent as a sequence of bytes and deals with the flow of data.
Every stream is associated with a class having member functions and operations for a particular kind of data flow. All the file handling operations in C++ use different types of stream for transferring data between different stations. Normally, the data is required to be flown(moved) between
  1. Memory To File (Writing)
  2. File To Memory (Reading)
  3. Memory To File and File To Memory (Writing and Reading)
In C++, there are different streams for all the above purposes. When working with files in C++, the following classes can be used:
  1. Ofstream : Ofstream or Output Stream is used to "output" or send the data from the program to a disc file. In simple words, this class is used for "Writing" purpose. The term "Writing" refers to either creating a new file or editing the contents of an existing file.
  2. Ifstream : Ifstream or Input Stream performs the task of "Reading" the contents of a file. Using "Ifstream" a file can be read either fully or partially. It is to be remembered that if the has been opened for "reading" we can not perform any "writing" task on it.
  3. Fstream : The "Fstream" or File Stream can be used for both "Writing" and "Reading" purposes.  If the user wishes to perform both the tasks in a program then instread of using both "Ifstream" and "Ofstream", the use of "Fstream" is recomended since it saves time as the file is not required to closed and reopened in for performing different operations.

Wednesday, August 17, 2011

Pure Virtual Function

Introduction
A "Pure Virtual Function" is a virtual function that is declared as "Virtual" in the base class and overridden in the derived class. A "Pure Virtual Function" does not have a body or definition in the containing class. To declare a "Pure Virtual Function", the function declaration is terminated by adding a "()=0" at the end to denote that the function has no body. A class that has at least one Pure Virtual Function is called an "Abstract Class"(See previous posts for an explanation on abstract class). All the classes that inherit from an "Abstract" Class must define or override all the pure virtual functions. If a child class fails to override a pure virtual function of the parent class the compiler will return an error.

Syntax

virtual return_type function_name()=0;

Example

#include

#include

class shape
{
       virtual void area()=0;
  };
  class rectangle : public shape
  {
       int length,breadth;
  public:
       rectangle(int l,int b)
       {
             length=l;
            breadth=b;
       }
       void showrect()
       {
             cout<<"\nLength "<
             cout<<"\nBreadth "<
       }
       void area()
       {
             int ar;
             ar=length*breadth;
             cout<<"\nArea of rectangle is "<
       }
  };
  class square : public shape
  {
       int side;
  public:
       square(int s)
       {
             side=s;
       }
       void showsquare()
       {
             cout<<"\nSide : "<
       }
       void area()
       {
             int ar;
             ar=side*side;
             cout<<"\nArea of Square : "<
       }
  };
 
void main()
  {
       clrscr();
       cout<<"\nRECTANGLE";
       rectangle rect(4,5);
       rect.showrect();
       rect.area();

     cout<<"\nSQUARE";
       square sq(9);
       sq.showsquare();
       sq.area();
}
 
Output

  RECTANGLE
  Length 4
  Breadth 5
  Area of rectangle is 20
  SQUARE
  Side : 9
  Area of Square : 81 

Thursday, August 11, 2011

Abstract Classes and Methods

Abstract Classes

The word "abstract" means "An  object which does not exist at any particular time or place, but rather exists as a type of thing (as an idea, or abstraction). In philosophy, an important distinction is whether an object is considered abstract or concrete. Abstract Classes in OOPs are those classes that do not represent anything real.
  1.  Still it may make sense to create such a class.
  2. All derived classes will inherit its code, thus the code has to be written only once.
  3. We call a class that we cannot create objects of Abstract.
  4. For example, there is no concrete vehicle, thus the class vehicle will be abstract.
  5. Concrete derived classes, such as Car or Motorcycle may inherit the code for wheels, seats, engines, ...
  6. Another reason is to get consistent behavior for same things - A wheel will thus always behave the same.
  7. Often most of the work goes into the abstract parent class.
Abstract Methods
An abstract method has no body or definition in the parent class, the child class must provide definitions for the abstract methods.
  1. An abstract class may not know how a method can be implemented.
  2. Still that method must be there 
  3. An Abstract Method is declared in a base class and must be implemented by all classes derived from it.
  4. Why? The (abstract) base class represents the concept while the derived classes are “only” the implementations.

Monday, August 8, 2011

Pure Virtual Function and Abstract Class.

Introduction
A Pure Virtual Function is a virtual function that has no body or definition in the containing class. The class that contains at least one pure virtual function is called an "Abstract Class". An abstract class is a class that can not be instantiated, that is, we can not create an object of an Abstract Class.  Since an abstract class can not be instantiated there is only one left to access its members - by inheriting it. All the classes that are sub class of an abstract class must provide the definition of the "pure virtual function". If a child class fails to define or override a pure virtual function, the compiler will display an error.
Typically, the pure virtual functions in an abstract base class are never implemented. Because no objects of that type are ever created, there is no reason to provide implementations, and the ADT works purely as the definition of an interface to objects which derive from it.
It is possible, however, to provide an implementation to a pure virtual function. The function can then be called by objects derived from the ADT, perhaps to provide common functionality to all the overridden functions. Listing below, this time with Shape as an ADT and with an implementation for the pure virtual function Draw(). The Circle class overrides Draw(), as it must, but it then chains up to the base class function for additional functionality.
In this example, the additional functionality is simply an additional message printed, but one can imagine that the base class provides a shared drawing mechanism, perhaps setting up a window that all derived classes will use.


1:     //Implementing pure virtual functions
2:
3:     #include 
4:
5:     enum BOOL { FALSE, TRUE };
6:
7:     class Shape
8:     {
9:     public:
10:       Shape(){}
11:       ~Shape(){}
12:       virtual long GetArea() = 0; // error
13:       virtual long GetPerim()= 0;
14:       virtual void Draw() = 0;
15:    private:
16:    };
17:
18:     void Shape::Draw()
19:    {
20:       cout << "Abstract drawing mechanism!\n";
21:    }
22:
23:    class Circle : public Shape
24:    {
25:    public:
26:          Circle(int radius):itsRadius(radius){}
27:          ~Circle(){}
28:          long GetArea() { return 3 * itsRadius * itsRadius; }
29:          long GetPerim() { return 9 * itsRadius; }
30:          void Draw();
31:    private:
32:       int itsRadius;
33:       int itsCircumference;
34:    };
35:
36:    void Circle::Draw()
37:    {
38:       cout << "Circle drawing routine here!\n";
39:       Shape::Draw();
40:    }
41:
42: 
43:    class Rectangle : public Shape
44:    {
45:    public:
46:          Rectangle(int len, int width):
47:             itsLength(len), itsWidth(width){}
48:          ~Rectangle(){}
49:          long GetArea() { return itsLength * itsWidth; }
50:          long GetPerim() {return 2*itsLength + 2*itsWidth; }
51:          virtual int GetLength() { return itsLength; }
52:          virtual int GetWidth() { return itsWidth; }
53:          void Draw();
54:    private:
55:       int itsWidth;
56:       int itsLength;
57:    };
58:
59:    void Rectangle::Draw()
60:    {
61:       for (int i = 0; i> choice;
103:
104:         switch (choice)
105:         {
106:            case 1: sp = new Circle(5);
107:            break;
108:            case 2: sp = new Rectangle(4,6);
109:            break;
110:            case 3: sp = new Square (5);
111:            break;
112:            default: fQuit = TRUE;
113:            break;
114:         }
115:         if (fQuit)
116:            break;
117:
118:         sp->Draw();
119:         cout << "\n";
120:      }
121:     return 0;
122: }

Output: (1)Circle (2)Rectangle (3)Square (0)Quit: 2
x x x x x x
x x x x x x
x x x x x x
x x x x x x
Abstract drawing mechanism!

(1)Circle (2)Rectangle (3)Square (0)Quit: 3
x x x x x
x x x x x
x x x x x
x x x x x
x x x x x
Abstract drawing mechanism!

(1)Circle (2)Rectangle (3)Square (0)Quit: 0

Analysis: On lines 7-16, the abstract data type Shape is declared, with all three of its accessor methods declared to be pure virtual. Note that this is not necessary. If any one were declared pure virtual, the class would have been an ADT.

The GetArea() and GetPerim() methods are not implemented, but Draw() is. Circle and Rectangle both override Draw(), and both chain up to the base method, taking advantage of shared functionality in the base class.

Saturday, August 6, 2011

Virtual Functions

A virtual function is a member function of the base class and which is redefined by the derived class. When a derived class inherits the class containing the virtual function, it has ability to redefine the virtual functions. A virtual function has a different functionality in the derived class. The virtual function within the base class provides the form of the interface to the function. Virtual function implements the philosophy of one interface and multiple methods. The virtual functions are resolved at the run time. This is called dynamic binding. The functions which are not virtual are resolved at compile time which is called static binding. A virtual function is created using the keyword virtual which precedes the name of the function.
Virtual functions are accessed using a base class pointer. A pointer to the base class can be created. A base class pointer can contain the address of the derived object as the derived object contains the subset of base class object. Every derived class is also a base class. When a base class pointer contains the address of the derived class object, at runtime it is decided which version of virtual function is called depending on the type of object contained by the pointer. Here is a program which illustrates the working of virtual functions.
A Virtual function is a function whic is declared in base class using the keyword virtual. We write the body of virtual function in the derived classes. Its purpose is to tell the compiler that what function we would like to call on the basis of the object of derived class. C++ determines which function to call at run time on the type of object pointer to.

Example

class Base{

 public:
virtual void fun1(void)
{
cout <<  "Base Class\n";
}
};
class Derived1 : public Base
{
public:
void fun1 (void)
{
cout <<  "Derived Class 1 \n";
}
};

class Derived2 : public Base
{
public:
void fun1 (void)
{
cout <<  "Derived Class 2\n";
}
};

int main(void)
{
Base b;
Base *bp;
Derived1 d1;
Derived2 d2;

bp = &b;
bp ->fun1(); //Executes the base class who function

bp = &d1;
bp ->fun1(); //Executes the Derived1 class who function

bp = &d2;
bp ->fun1(); //Executes the Derived2 class who function
}

 
Output

  Base Class
  Derived Class 1
  Derived Class 2
 

Thursday, August 4, 2011

Static and Dynamic Polymorphism

Static and Dynamic Polymophism

One feature in object-oriented programming languages which is essential to implementing polymorphism is dynamic bindning of functions. Procedural programming languages (like C, Pascal and COBOL etc.) offer static binding.

Static (or early) binding is the concept of resolving a function/method call at compile time.
Function/subroutine calls are bound to specific computer memory locations where functions/subroutines are placed at compile time.
Static polymorphism refers to an entity existing in different physical forms simultaneously. Static polymorphism involves binding of functions on the basis of number, type and sequence, of their arguments. The various types of parameters are specified in the function declaration, and therefore the function can be bound to the class at compile tune. This form of associations is called binding. The term early binding terms from the fact when the program is executed, the calls are already bounds to the appropriate functions. The resolution is on the basis of number, type, arid sequence of argument declared for each form of the function. Consider the following function declarations:
void add (int, int);
void add (float, float);
Now, if the function add() is invoked, the parameters passed to it will determine which version of the function will be executed.This resolution is done at compile time

Dynamic (or late) binding is the concept of resolving a method call at run time. Dynamic polymorphism, refers to an entity changing its form depending on the circumstances. A function is said to exhibit dynamic polymorphism when it exists in more than one form, and calls to its various forms are resolved dynamically when the program is executed. Then term late binding refers to the resolution of the function to their associated methods at run-time instead of compile time. This feature increases the flexibility of the program by allowing the appropriate method to be invoked, depending on the content. The compiler is unable to bind a call to a method since resolution depends on the content of the call.
The information available to the compiler at compile time, is the name of an operation, and a branch of the class hierarchy where this operation is defined:
myVehicle -> stop;
At run-time, the correct version of the stop method is selected, i.e. the version which corresponds to the class of the object which the variable myVehicle currently refers to, e.g. stop for Cars, stop for Plane etc.
Note that, the code on the sender side of the program will work even if we later on extend the system to handle new types of vehicles, because the sender expresses WHAT is to be done, instead of HOW. This is an example of polymorphism at work.

Monday, August 1, 2011

String Comparison Using The "==" Operator


#include "iostream.h"
#include "conio.h"
#include "string.h"
class string
{
      char str[20];
public:
      string(char s[])
      {
            strcpy(str,s);
      }
      void print()
      {
            cout<<"\n"<
      }
      int operator==(string s)
      {
            if(strcmp(str,s.str)==0)
                  return 1;
            else
                  return 0;
      }
};


void main()
{

      clrscr();
      string s1("Overloading"),s2("Overloading");
      int res;
      if(s1==s2)
           cout<<"\nSame String";
      else
           cout<<"\nDifferent String";
}



Output

Same String


String Concatenation Using + operator

#include "stdio.h"
#include "conio.h"
#include "string.h"
class string
{
                char str[20];
public:
                string()
                {}
                string(char s[])
                {
                                strcpy(str,s);
                }
                void print()
                {
                                cout<<"\n"<
                }
                string operator+(string s)
                {
                                string temp;                                                     strcpy(temp.str,str);                              
                           strcat(temp.str,s.str);                               
                         return temp;
                }
};

 void main()
{
                clrscr();
                string s1("Operator"),s2("Overloading"),s3;
                s3=s1+s2;
                s3.print();
}

Output

OperatorOverloading