Popular Posts

Sunday 4 March 2012

C++ - Model Programs

 

Polymorphism 


Contents of this section:

  1. Pointer to derived objects
  2. Virtual functions and polymorphism

1. Pointer to derived objects

    Code Listing: 

// File:    ~ftp/pub/class/cplusplus/Poly/PtrDerived.cpp
// Purpose: Using base pointers on derived class objects.
#include <iostream>
#include <cstring>
using namespace std;

class B_class {
  char author[80];
public:
  void put_author(char *s) { strcpy(author, s); }
  void show_author() { cout << author << "\n"; }
} ;

class D_class : public B_class {
  char title[80];
public:
  void put_title(char *num) {
    strcpy(title, num);
  }
  void show_title() {
    cout << "Title: ";
    cout <<  title << "\n";
  }
};

int main()
{
  B_class *p;
  B_class B_ob;

  D_class *dp;
  D_class D_ob;

  p = &B_ob;  // address of base

  // Access B_class via pointer.
  p->put_author("Tom Clancy");

  // Access D_class via base pointer.
  p = &D_ob;
  p->put_author("William Shakespeare");

  // Show that each author went into proper object.
  B_ob.show_author();
  D_ob.show_author();
  cout << "\n";

  /* Since put_title() and show_title() are not part
     of the base class, they are not accessible via
     the base pointer p and must be accessed either
     directly, or, as shown here, through a pointer to the
     derived type.
  */
  dp = &D_ob;
  dp->put_title("The Tempest");
  p->show_author(); // either p or dp can be used here.
  dp->show_title( );

  return 0;
}

    Running session:

@9:35am merc-hu[76]% CC -LANG:std PtrDerived.cpp -o PtrDerived
@9:35am merc-hu[77]% PtrDerived
Tom Clancy
William Shakespeare

William Shakespeare
Title: The Tempest
@9:35am merc-hu[78]% 

2. Virtual functions and polymorphism

Code listing:

// File:    ~ftp/pub/class/cplusplus/Poly/VirtualPoly.cpp
// Purpose: Vitual function and polymorphism

#include <iostream>
using namespace std;

class figure {
protected:
  double x, y;
public:
  void set_dim(double i, double j=0) {
    x = i;
    y = j;
  }
  virtual void show_area() {
    cout << "No area computation defined ";
    cout << "for this class.\n";
  }
} ;

class triangle : public figure {
  public:
    void show_area() {
      cout << "Triangle with height ";
      cout << x << " and base " << y;
      cout << " has an area of ";
      cout << x * 0.5 * y << ".\n";
    }
};

class square : public figure {
  public:
    void show_area() {
      cout << "Square with dimensions ";
      cout << x << "x" << y;
      cout << " has an area of ";
      cout << x *  y << ".\n";
    }
};
class circle : public figure {
  public:
    void show_area() {
      cout << "Circle with radius ";
      cout << x;
      cout << " has an area of ";
      cout << 3.14 * x * x << ".\n";
    }
} ;

int main()
{
  figure *p; // create a pointer to base type

  triangle t; // create objects of derived types
  square s;
  circle c;

  p = &t;
  p->set_dim(10.0, 5.0);
  p->show_area();

  p = &s;
  p->set_dim(10.0, 5.0);
  p->show_area();

  p = &c;
  p->set_dim(9.0);
  p->show_area();

  return 0;
}

Running session:

@9:41am merc-hu[82]% CC -LANG:std VirtualPoly.cpp -o VirtualPoly
@9:41am merc-hu[83]% VirtualPoly
Triangle with height 10 and base 5 has an area of 25.
Square with dimensions 10x5 has an area of 50.
Circle with radius 9 has an area of 254.34.

Structure 


Contents of this section:

  1. A simple program demonstrating structure
  2. Nested structure
  3. Using functions in structure

1. A simple program demonstrating structure

    Code Listing: 

// File Name: ~ftp/pub/class/cplusplus/Structure/StrucSimple.cpp
// Purpose:   Demonstrates the use of structure in C++.
//            Stores some personal data in a structure, then prints
//            the info out.

#include <iostream>
using namespace std;

int main()
{
        // Defining a structure
        struct PersonalData
        {
                char *FirstName;
                char *LastName;
                char *Birthday;  // in the format of 12/30/1978
                int  PhoneNum;
        }; // don't forget the ending ";"

        // Declaring a variable of type PersonalData
        PersonalData PersonOne;

        // Populate PersonOne with data
        PersonOne.FirstName = "John";
        PersonOne.LastName = "Doe";
        PersonOne.Birthday = "12/30/1978";
        PersonOne.PhoneNum = 5855555;

        // Print the data out
        cout << "PersonOne's First name is: " << PersonOne.FirstName << endl;
        cout << "PersonOne's Last name is: " << PersonOne.LastName<< endl;
        cout << "PersonOne's Birthday is: " << PersonOne.Birthday<< endl;
        cout << "PersonOne's Phone number is: " << PersonOne.PhoneNum<< endl;

        return 0;
}

    Running session:

@9:51am merc-hu[34]% CC -LANG:std StrucSimple.cpp -o StrucSimple
@9:52am merc-hu[35]% StrucSimple
PersonOne's First name is: John
PersonOne's Last name is: Doe
PersonOne's Birthday is: 12/30/1978
PersonOne's Phone number is: 5855555
@9:52am merc-hu[36]% 

2. Nested structure

Code listing:

// File Name: ~ftp/pub/class/cplusplus/Structure/StrucSimple.cpp
// Purpose:   Demonstrates the use of nested structure in C++.
//            Stores some personal data in a structure, then prints
//            the info out.

#include <iostream>
using namespace std;

int main()
{
        // Defining a structure for name
        struct Name
        {
                char *FirstName;
                char *LastName;
        };

        struct PersonalData
        {
                Name NameField; // struct as a memeber
                char *Birthday;  // in the format of 12/30/1978
                int  PhoneNum;
        }; // don't forget the ending ";"

        // Declaring a variable of type PersonalData
        PersonalData PersonOne;


        PersonOne.NameField.FirstName = "John";
        PersonOne.NameField.LastName = "Doe";

        // Populate PersonOne with data
        PersonOne.Birthday = "12/30/1978";
        PersonOne.PhoneNum = 5855555;

        // Print the data out
        cout << "First name is: " << PersonOne.NameField.FirstName << endl;
        cout << "Last name is: " << PersonOne.NameField.LastName<< endl;
        cout << "Birthday is: " << PersonOne.Birthday<< endl;
        cout << "Phone number is: " << PersonOne.PhoneNum<< endl;

        return 0;
}

Running session:

@9:59am merc-hu[45]% CC -LANG:std StructNested.cpp -o StructNest
@10:00am merc-hu[47]% StructNest 
First name is: John
Last name is: Doe
Birthday is: 12/30/1978
Phone number is: 5855555
@10:00am merc-hu[48]% 

3. Using functions in structure

    Code Listing: 

 
// File Name: ~ftp/pub/class/cplusplus/Structure/StrucSimple.cpp
// Purpose:   Demonstrates the use of funciton in C++ struct.
//            Stores some personal data in a structure, then prints
//            the info out.

#include <iostream>
using namespace std;

int main()
{
        
        struct PersonalData
        {
                char *FirstName;
                char *LastName;
                char *Birthday;  // in the format of 12/30/1978
                int  PhoneNum;

                // struc can also have member functions
                void PrintDat()
                {
                        // Print the data out
                        cout << "First name is: " << FirstName << endl;
                        cout << "Last name is: " << LastName << endl;
                        cout << "Birthday is: " << Birthday << endl;
                        cout << "Phone number is: " << PhoneNum << endl;
                }
        }; // don't forget the ending ";"

        // Declaring a variable of type PersonalData
        PersonalData PersonOne;

        // Populate PersonOne with data
        PersonOne.FirstName = "John";
        PersonOne.LastName = "Doe";
        PersonOne.Birthday = "12/30/1978";
        PersonOne.PhoneNum = 5855555;

        PersonOne.PrintDat();
        return 0;
}

    Running session:

@10:07am merc-hu[51]% CC -LANG:std StrucFunc.cpp -o StrucFunc
@10:08am merc-hu[52]% StrucFunc
First name is: John
Last name is: Doe
Birthday is: 12/30/1978
Phone number is: 5855555

Formatted I/O, File I/O 


Contents of this section:

  1. Formatted I/O using ios member functions
  2. Formatted I/O using I/O manipulators
  3. Define your own I/O manipulators
  4. File I/O: Writing to a text file
  5. File I/O: Reading from a text file

1. Formatted I/O using ios member functions

    Code Listing: 

// File name: ~ftp/pub/class/cplusplus/IO/IOMember.cpp
// Purpose:   Demonstrating formatted IO using ios member functions

#include <iostream>
using namespace std;

int main()
{
 float num[5] = {1.0, -1.2345, 2350.1, 23.4, 45.34};
 int i;

  cout.setf(ios::showpos); // show the + sign before positive numbers
   cout.setf(ios::scientific); // use scientific notation
   cout.precision(2); // two digits after decimal point
 
 for(i = 0; i < 5; i++)
 {
    cout.width(20);    // use 10 spaces for the number
  cout.fill('$');    // pad with $
        cout << num[i] << endl;
 }

  return 0;
}

    Running session:

mercury[148]% CC -LANG:std IOMember.cpp -o IOMember
mercury[149]% IOMember
$$$$$$$$$$$+1.00e+00
$$$$$$$$$$$-1.23e+00
$$$$$$$$$$$+2.35e+03
$$$$$$$$$$$+2.34e+01
$$$$$$$$$$$+4.53e+01
mercury[150]% 

2. Formatted I/O using I/O manipulators

Code listing:

// File name: ~ftp/pub/class/cplusplus/IO/IOMember.cpp
// Purpose:   Demonstrating formatted IO manipulators

#include <iostream>
#include <iomanip>
using namespace std;

int main()
{
 float num[5] = {1.0, -1.2345, 2350.1, 23.4, 45.34};
 int i;

  cout << setiosflags(ios::showpos);
 cout << setiosflags(ios::scientific); 
 cout << setprecision(2); 
 
 for(i = 0; i < 5; i++)
 {
    cout << setw(20);    
    cout << setfill('$');    
        cout << num[i] << endl;
 }

  return 0;
}

Running session:

mercury[156]% CC -LANG:std IOManip.cpp -o IOManip
mercury[157]% IOManip 
$$$$$$$$$$$+1.00e+00
$$$$$$$$$$$-1.23e+00
$$$$$$$$$$$+2.35e+03
$$$$$$$$$$$+2.34e+01
$$$$$$$$$$$+4.53e+01
mercury[158]% 

3. Define your own I/O manipulators

Code listing:

// File name: ~ftp/pub/class/cplusplus/IO/IOUserManip.cpp
// Purpose:   Demonstrates how to define an IO manipulator function
//            of your own.

#include <iostream>
#include <iomanip>
using namespace std;

// function prototype for a user-defined IO manipulator function
ostream &SetHex(ostream &stream);

int main()
{
 int input;
 cout << "Enter an integer: " ;
 cin  >> input;

 cout << "Hexdecimal is: ";
 
 // call the SetHex function so that the input
 // integer will be printed out in hexdecimal
 cout << SetHex << input << endl;
 return 0;
}

// definition of a user defined I/O manipulate function
ostream &SetHex(ostream &stream)
{
 // Set output base to be hexdecimal.
 // Use ios::basefield to make sure that all other
 // field in basefield is cleared before setting it
 // to hex.
 stream.setf(ios::hex,ios::basefield); 
 return stream;
}

Running session:

mercury[200]% CC -LANG:std IOUserManip.cpp -o IOUserManip
mercury[201]% IOUserManip
Enter an integer: 19
Hexdecimal is: 13
mercury[202]% 
 

4. File I/O: Writing to a text file

Code Lising

// File name: ~ftp/pub/class/cplusplus/IO/FileWrite.cpp
// Purpose:   Write to text file

#include <iostream>
#include <fstream>
using namespace std;

int main()
{
 char OutFile[80]; // output file name
 ofstream OutStream;  // open an output stream
 
 cout << "Please enter output file name: " ;
 cin >> OutFile;

 OutStream.open(OutFile, ios::out | ios::trunc);
 
 // make sure file is successfully opened
 if(!OutStream)
 {
  cout << "Error open file " << OutFile << " for writing\n";
  return 1;
 }
 
 // Write the following two lines to file
 OutStream<<"It is easier to resist at the beginning than at the end.\n";
 OutStream <<"                 -- Leonardo da Vinci" << endl;

 OutStream.close(); // close output stream

 cout << "Content written to " << OutFile <<".\n";

 return 0;

}

Running Session

mercury[298]% CC -LANG:std FileWrite.cpp -o FileWrite
mercury[299]% FileWrite
Please enter output file name: out.txt
Content written to out.txt.
mercury[300]% 

5. File I/O: Reading from a text file

Code Lising

// File name: ~ftp/pub/class/cplusplus/IO/FileRead.cpp
// Purpose:   Read the content of a text file and print it
//            out on the screen

#include <iostream>
#include <fstream>
using namespace std;

int main()
{
 char InFile[80];  // input file name
 char ch;
 
 ifstream InStream;

 cout << "This program reads the content of a file and ";
 cout << "prints it out on the screen." << endl;

 cout << "Enter input file name: " ;
 cin >> InFile;

 // Open file for input
 // in.open(fin); also works
 InStream.open(InFile, ios::in);

 // ensure file is opened successfully
 if(!InStream)
 {
  cout << "Error open file " << InFile << endl;
  return 1;
 }
 
 cout << "Here is the content of " << InFile << ":\n";
 // Read in each character until eof character is read.
 // Output it to screen.
 while (!InStream.eof()) {
  //Read each character.
  InStream.get(ch);    

  // make sure we don't write any odd characters on screen
  if (!InStream.eof()) 
  {
   cout << ch;  //Write to screen
  }
 }

 InStream.close();
}

Running Session

mercury[243]% CC -LANG:std FileRead.cpp -o FileRead
mercury[244]% FileRead
This program reads the content of a file and prints it out on the screen.
Enter input file name: test.txt
Here is the content of test.txt:
It is easier to resist at the beginning than at the end.

Functions 


Contents of this section:

  1. A Simple program finding the absolute value of an integer (without using function)
  2. A Simple program finding the absolute value of an integer (using a function)

1. A Simple program without using functions

    Code Listing: 

//
// File name: ~ftp/pub/class/cplusplus/Functions/Absolute1.cpp
// Purpose:   This program find the absolute value of an integer
//       without using a function
//

#include <iostream>
using namespace std;

int main()
{
 int number;
 int abs_number;

 // Ask for input
 cout << "This program finds the absolute value of an integer." << endl;
 cout << "Enter an integer (positive or negative): ";
 cin >> number;
 
 // Find the absolute value
 if(number >= 0)
 {
  abs_number = number;
 }
 else
  abs_number = -number;
 
 // Print out output
 cout << "The absolute value of " << number << " is " << abs_number;
 cout << endl;
 return 0;
}

    Running session:

mercury[50]% CC -LANG:std Absolute1.cpp -o Absolute1
mercury[51]% Absolute1
This program finds the absolute value of an integer.
Enter an integer (positive or negative): -45
The absolute value of -45 is 45
mercury[52]% Absolute1
This program finds the absolute value of an integer.
Enter an integer (positive or negative): 0
The absolute value of 0 is 0
mercury[53]% Absolute1
This program finds the absolute value of an integer.
Enter an integer (positive or negative): 9
The absolute value of 9 is 9
mercury[54]% 

2. The same program using function

Code listing:

//
// File name: ~ftp/pub/class/cplusplus/Functions/Absolute2.cpp
// Purpose:   This program finds the absolute value of an integer
//       using a function
//

int Abs(int i); // Function prototype
int main()
{
 int number;
 int abs_number;

 cout << "This program finds the absolute value of an integer." << endl;
 cout << "Enter an integer (positive or negative): ";
 cin >> number;
 
 // Calling the function Abs()
 abs_number = Abs(number);
 cout << "The absolute value of " << number << " is " << abs_number;
 cout << endl;
 return 0;
}
// Function definition
int Abs(int i)
{
 if( i >= 0)
  return i;
 else
  return -i;
}

Running session:

mercury[56]% CC -LANG:std Absolute2.cpp -o Absolute2
mercury[57]% Absolute2
This program finds the absolute value of an integer.
Enter an integer (positive or negative): -45
The absolute value of -45 is 45
mercury[58]% Absolute2
This program finds the absolute value of an integer.
Enter an integer (positive or negative): 0
The absolute value of 0 is 0
mercury[59]% Absolute2
This program finds the absolute value of an integer.
Enter an integer (positive or negative): -9
The absolute value of -9 is 9

Inheritance 


Contents of this section:

  1. A simple program demonstrating inheritance
  2. Using protected members
  3. Protected inheritance
  4. Multiple inheritance
  5. Calling base class's constructor in derived class

1. A simple program demonstrating inheritance

    Code Listing: 

 
// File:    ~ftp/pub/class/cplusplus/Inheritance/SimpleInherit.cpp
// Purpose: A simple program showing inheritance

#include <iostream>
using namespace std;

class base {
  int i, j;
public:
  void set(int a, int b) { i = a; j = b; }
  void show() { cout << i << " " << j << "\n"; }
};

// inheritance
class derived : public base {
  int k;
public:
  derived(int x) { k = x; }
  void showk() { cout << k << "\n"; }
};

int main()
{
  derived ob(3);

  ob.set(1, 2); // access member of base
  ob.show();    // access member of base

  ob.showk();   // uses member of derived class

  return 0;
}

    Running session:

 
@2:32pm merc-hu[211]% CC -LANG:std SimpleInherit.cpp -o SimpleInherit
@2:33pm merc-hu[212]% SimpleInherit 
1 2
3
@2:33pm merc-hu[213]% 

2. Using protected members

Code listing:

// File:    ~ftp/pub/class/cplusplus/inheritance/ProtectedMember.cpp
// Purpose: Inherite protected members of the base class

#include <iostream>
using namespace std;

class base {
protected:
  int i, j; // private to base, but accessible to derived
public:
  void set(int a, int b) { i = a; j = b; }
  void show() { cout << i << " " << j << "\n"; }
};

class derived : public base {
  int k;
public:
  // derived may access base's i and j
  void setk() { k = i*j; }

  void showk() { cout << k << "\n"; }
};

int main()
{
  derived ob;

  ob.set(2, 3); // OK, known to derived
  ob.show();    // OK, known to derived

  ob.setk();
  ob.showk();

  return 0;
}

Running session:

@10:48am merc-hu[18]% CC -LANG:std ProtectedMember.cpp -o ProtectedMember
@10:49am merc-hu[19]% ProtectedMember
2 3
6
@10:50am merc-hu[20]% 

3. Protected inheritance

    Code Listing: 

// File:    ~ftp/pub/class/cplusplus/Inheritance/ProtectedInheritance.cpp
// Purpose: using protected for inheritance of a base class

#include <iostream>
using namespace std;

class base {
  int i;
protected:
  int j;
public:
  int k;
  void seti(int a) { i = a; }
  int geti() { return i; }
};

// Inherit base as protected.
class derived : protected base {
public:
  void setj(int a) { j = a; } // j is protected here
  void setk(int a) { k = a; } // k is also protected
  int getj() { return j; }
  int getk() { return k; }
};

int main()
{
  derived ob;

  /* This next line is illegal because seti() is
     a protected member of derived, which makes it
     inaccessible outside of derived. */
//  ob.seti(10);

//  cout << ob.geti(); // illegal -- geti() is protected
//  ob.k = 10; // also illegal because k is protected

  // these next statements are OK
  ob.setk(10);
  cout << ob.getk() << ' ';
  ob.setj(12);
  cout << ob.getj() << ' ';

  return 0;
}

    Running session:

@10:59am merc-hu[25]% CC -LANG:std ProtectedInheritance.cpp -o ProtectedInheritance
@10:59am merc-hu[26]% ProtectedInheritance 
10 12 
@10:59am merc-hu[27]% 
��

4. Multiple inheritance 

    Code Listing: 

// File:   ~ftp/pub/class/cplusplus/Inheritance/MulInhert.cpp
// Purpose: An example of multiple base classes.

#include <iostream>
using namespace std;

class base1 {
protected:
  int x;
public:
  void showx() { cout << x << "\n"; }
};

class base2 {
protected:
  int y;
public:
  void showy() { cout << y << "\n"; }
};

// Inherit multiple base classes.
class derived: public base1, public base2 {
public:
  void set(int i, int j) { x = i; y = j; }
};

int main()
{
  derived ob;

  ob.set(10, 20); // provided by derived
  ob.showx();     // from base1
  ob.showy();     // from base2

  return 0;
}

    Running session:

@11:04am merc-hu[32]% CC -LANG:std MulInherit.cpp -o MulInherit
@11:05am merc-hu[33]% MulInherit 
10
20
@11:05am merc-hu[34]% 
��

5. Calling base class's constructor in derived class 

    Code Listing: 

// File:    ~ftp/pub/class/cplusplus/Inheritance/BaseConst.cpp
// Purpose: demonstrate how to call base class's constructor

#include <iostream>
using namespace std;

class base1 {
protected:
  int i;
public:
  base1(int x) { i = x; cout << "Constructing base1\n"; }
  ~base1() { cout << "Destructing base2\n"; }
};

class base2 {
protected:
  int k;
public:
  base2(int x) { k = x; cout << "Constructing base2\n"; }
  ~base2() { cout << "Destructing base2\n"; }
};

class derived: public base1, public base2 {
  int j;
public:
  derived(int x, int y, int z): base1(y), base2(z)
    { j = x; cout << "Constructing derived\n"; }

  ~derived() { cout << "Destructing derived\n"; }
  void show() { cout << i << " " << j << " " << k << "\n"; }
};

int main()
{
  derived ob(3, 4, 5);

  ob.show();  // displays 4 3 5

  return 0;
}

 

    Running session:

@11:11am merc-hu[35]% CC -LANG:std BaseConst.cpp -o BaseConst
@11:12am merc-hu[36]% BaseConst
Constructing base1
Constructing base2
Constructing derived
4 3 5
Destructing derived
Destructing base2
Destructing base2

 

References 


Contents of this section:

  1. A simple program demonstrating references
  2. Function: passing by references

1. A simple program demonstrating references

    Code Listing: 

// File name: ~ftp/pub/class/cplusplus/Reference/RefSimple.cpp
// Purpose:   A simple program demonstrating the use of reference

#include <iostream>
using namespace std;

int main()
{
 int Len, Wid;     // declare int variables

 // Create references to int variables.
        // Now rLen and Len are aliases to each other,
        // and rWid and Wid are also aliases to each other.
 int &rLen = Len;
 int &rWid = Wid; 
 
 // Initialized the two int variables
 Len = 10;         // rLen is also initialized to be 10
 Wid = 20;         // rWid is also initialized to be 20

 // Printing out the values for int and int references
 cout << "Len is: " << Len << ", and  Wid is: " << Wid << endl;
 cout << "rLen is: " << rLen << ", and rWid is: " << rWid << endl;
 cout << endl;
 
 // Printing out the address of int and references to int
 cout << "Address of Len is: " << &Len << endl;
 cout << "Address of rLen is: "  << &rLen << endl;
 if(&Len == &rLen)
 {
  cout << "Address of Len is equal to address of rLen!" << endl;
 }
 cout << "Address of Wid is: " << &Wid << endl;
 cout << "Address of rWid is: "  << &rWid << endl;
 if(&Wid == &Wid)
 {
  cout << "Address of Wid is equal to address of rWid!" << endl;
 }

 return 0;
}

    Running session:

mercury[39]% CC -LANG:std RefSimple.cpp -o RefSimple
mercury[40]% RefSimple
Len is: 10, and  Wid is: 20
rLen is: 10, and rWid is: 20

Address of Len is: 2147429924
Address of rLen is: 2147429924
Address of Len is equal to address of rLen!
Address of Wid is: 2147429932
Address of rWid is: 2147429932
Address of Wid is equal to address of rWid!
mercury[41]% 

2. Function: passing by references

Code listing:

// File name: ~ftp/pub/class/cplusplus/Reference/RefFunction.cpp
// Purpose:   Demonstrates pass by reference in a function

#include <iostream>
using namespace std;

void swap(int &i, int &j);  // function prototype for swapping two values

int main()
{
 int NumOne = 0;
 int NumTwo = 0;

 cout << "Please enter two integers: " << endl;

 cout << "Enter value for NumOne: " ;
 cin >> NumOne;

 cout << "Enter value for NumTwo: " ;
 cin >> NumTwo;

 cout << "Before swapping, NumOne is: " << NumOne << endl;
 cout << "Before swapping, NumTwo is: " << NumTwo<< endl;

 swap(NumOne, NumTwo);

 cout << "After swapping, NumOne is: " << NumOne << endl;
 cout << "After swapping, NumTwo is: " << NumTwo<< endl;

 return 0;
}

// function definition for swap()

void swap(int &i, int &j)
{
 int temp;

 temp = i;
 i = j;
 j = temp;

}

Running session:

mercury[51]% CC -LANG:std RefFunction.cpp -o RefFunction
mercury[52]% RefFunction
Please enter two integers: 
Enter value for NumOne: 10
Enter value for NumTwo: 20
Before swapping, NumOne is: 10
Before swapping, NumTwo is: 20
After swapping, NumOne is: 20
After swapping, NumTwo is: 10

 

 

Array 


Contents of this section:

  1. One dimensional integer array
  2. One dimensional character array (C-string)
  3. Two dimensional integer array
  4. Two dimensional character array (Array of strings)

1. One dimensional integer array

    Code Listing: 

// Author:    Herbert Schildt
// File name: ~ftp/pub/class/cpluslus/Array1.cpp
// Purpose:   Read 10 integers into an array and then print
//       them out

#include <iostream>
using namespace std;

int main()
{
 int sample[10]; // this reserves 10 integer elements
 int t;

 // load the array
 for(t = 0; t < 10; t++)
  sample[t] = t;

 // display the array
 for(t = 0; t < 10; ++t)
  cout << sample[t] << ' ' ;
 
 return 0;
}

    Running session:

mercury[34]% CC -LANG:std Array1.cpp -o Array1
mercury[35]% Array1
0 1 2 3 4 5 6 7 8 9 mercury[36]% 
mercury[36]% 

2. One dimensional character array (C-string)

Code listing:

// File name: ~ftp/pub/class/cplusplus/Array/Array2.cpp
// Purpose:   Demonstrate the use of character array.
//       Ask for the user's name and print it out.

#include <iostream>
#include <stdlib.h> //for newer compilers, include <cstdlib>
using namespace std;

int main()
{
 char name[32]; // big enough to hold 32 characters

 // prompt for the name
 cout << "What's your name?" << endl;
 gets(name); // read a string from the key board.
 cout << "Hello! " << name << "!"  << endl;

 return 0;
}

Running session:

mercury[41]% CC -LANG:std Array2.cpp -o Array2
mercury[43]% Array2
What's your name?
Bruce Lee
Hello! Bruce Lee!
mercury[44]% 

3. Two dimensional integer array

Code listing:

// Author:    Herbert Schildt 
// Modified:  Qiang Hu
// File name: ~ftp/pub/class/cplusplus/Array/Array3.cpp
// Purpose:   Use sqrs[][] -- two dimentional integer
//       array to store integers from 1 to 10 and
//       their squares.  
//            Ask user for a number, then look up this
//        number in the array and then print out its
//            corresponding square.

#include <iostream>
using namespace std;

int main()
{
  // C++ allows for the initialization of arrays.  In the following,
  // we are initializing a 10x2 integer array. After initialization,
  // sqrs[0][0] = 1
  // sqrs[0][1] = 1
  // sqrs[1][0] = 2
  // sqrs[1][1] = 4 
  // and so on
  int sqrs[10][2] = { 
         {1, 1}, 
  {2, 4}, // The square of 2 is 4,and so on
  {3, 9}, 
  {4, 16}, 
  {5, 25}, 
  {6, 36}, 
  {7, 49}, 
  {8, 64}, 
  {9, 81}, 
  {10, 100} 
  };

  int i, j;

  cout << "Enter a number between 1 and 10: ";
  cin >> i;

  // look up i
  for(j = 0; j < 10; j++) 
    if(sqrs[j][0] == i) break; // break from loop if i is found 
  cout << "The square of " << i << " is " ;
  cout << sqrs[j][1] << endl;

  return 0;
}

Running session:

mercury[66]% CC -LANG:std Array3.cpp -o Array3
mercury[67]% Array3
Enter a number between 1 and 10: 6
The square of 6 is 36
mercury[68]% 
 

4. Two dimensional character array (Array of Strings)

Code Lising

// Author:   Herbert Schildt
// Modified: Qiang Hu
// File name: ~ftp/pub/class/cplusplus/Array/Array4.cpp
// Purpose:  A simple employee database program.

#include <iostream>
using namespace std;

// function prototyping
int menu();    // funciton to display the menu
void enter();  // function to enter info
void report(); // function to print report

// Global variables:
char name[2][80];  // this array holds employee names
char phone[2][20]; // their phone numbers
float hours[2];    // hours worked per week
float wage[2];     // wage
int choice;

int main()
{
  do {
    choice = menu(); // get selection
    switch(choice) {
      case 0: break;
      case 1: enter();
        break;
      case 2: report();
        break;
      default: cout << "Try again.\n\n";
    }
  } while(choice != 0);

  return 0;
}

// Return a user's selection.
int menu()
{
  int choice;

  cout << "0. Quit\n";
  cout << "1. Enter information\n";
  cout << "2. Report information\n";
  cout << "\nChoose one: ";
  cin >> choice;

  return choice;
}

// Enter information.
void enter()
{
  int i;
  for(i=0; i<2; i++) {
    cout << "Enter last name: ";
    cin >> name[i];
    cout << "Enter phone number: ";
    cin >> phone[i];
    cout << "Enter number of hours worked: ";
    cin >> hours[i];
    cout << "Enter wage: ";
    cin >> wage[i];
  }
}

// Display report.
void report()
{
  int i;

  for(i=0; i<2; i++) {
    cout << name[i] << ' ' << phone[i] << '\n';
    cout << "Pay for the week: " << wage[i] * hours[i];
    cout << '\n';
  }
}

Running Session

mercury[81]% CC -LANG:std Array4.cpp -o Array4
mercury[82]% Array4
0. Quit
1. Enter information
2. Report information

Choose one: 1
Enter last name: Smith
Enter phone number: 5556666
Enter number of hours worked: 30
Enter wage: 23.40
Enter last name: Bush
Enter phone number: 6668888
Enter number of hours worked: 20
Enter wage: 40.00
0. Quit
1. Enter information
2. Report information

Choose one: 2
Smith 5556666
Pay for the week: 702
Bush 6668888
Pay for the week: 800
0. Quit
1. Enter information
2. Report information

 

 

 

Pointers 


Contents of this section:

  1. A simple program using pointers
  2. Pointer to characters
  3. Pointer arithmetic
  4. Array of pointers

1. A simple program using pointers

    Code Listing: 

// File name: ~ftp/pub/class/cplusplus/Pointer/PointerSimple.cpp
// Purpose:   A simple program demonstrating the use of pointers.

#include <iostream>
using namespace std;

int main()
{
 // declare an integer and a float variable
 int IntNum; 
 float FloatNum;
 
 // declare integer and float pointers
 int *pIntNum;
 float *pFloatNum;
 
 // initialize the integer and float variables
 IntNum = 10;
 FloatNum = 12.34;
 
 // store addresses in pointers
 pIntNum = &IntNum;
 pFloatNum = &FloatNum;

 // print out the original values
        cout << "Before increment: " << endl;
 cout << "\t IntNum is: " << IntNum << endl;
 cout << "\t FloatNum is: " << FloatNum << endl;
 
 // note that we need to dereference a pointer in order
 // to extract the value it contains.
 cout << "\t pIntNum contains: " << *pIntNum << endl;
 cout << "\t pFloatNum contains: " << *pFloatNum << endl;

 // increment values of the integer and float variables 
 (*pIntNum)++;  // dereference and then increment
 (*pFloatNum)++;

 // print out the values after increment
        cout << "After increment: " << endl;
 cout << "\t IntNum is: " << IntNum << endl;
 cout << "\t FloatNum is: " << FloatNum << endl;

 cout << "\t pIntNum contains: " << *pIntNum << endl;
 cout << "\t pFloatNum contains: " << *pFloatNum << endl;

 return 0;
}

    Running session:

mercury[5]% CC -LANG:std PointerSimple.cpp -o PointerSimple
mercury[6]% PointerSimple
Before increment: 
         IntNum is: 10
         FloatNum is: 12.34
         pIntNum contains: 10
         pFloatNum contains: 12.34
After increment: 
         IntNum is: 11
         FloatNum is: 13.34
         pIntNum contains: 11
         pFloatNum contains: 13.34

2. Pointer to characters

Code listing:

// File name: ~ftp/pub/class/cplusplus/Pointer/PointerChar.cpp
// Purpose:   demonstrate the use of pointer to char

#include <iostream>
#include <stdio.h> // use <cstdio> for newer compilers.
using namespace std;

int main()
{
 // a pointer to char is initialized with a string literal
 char *Buffer = "Dummy content.";
 
 cout << "Original content of Buffer:--> " << Buffer << endl;
 cout << "Enter a sentense: " << endl;

 // use gets() to get the whole line.
 // cout would only get the first word.
 gets(Buffer);
 cout << "Now the Buffer contains:--> " << endl;
 cout << Buffer << endl;
 return 0;
}

Running session:

mercury[156]% CC -LANG:std PointerChar.cpp -o PointerChar
mercury[10]% PointerChar
Original content of Buffer:--> Dummy content.
Enter a sentense: 
This is my sentense!
Now the Buffer contains:--> 
This is my sentense!
mercury[11]% 

3. Pointer Arithmetic

Code listing:

// File name:  ~ftp/pub/class/cplusplus/Pointer/PointerArith.cpp
// Purpose:    Demonstrates pointer arithmetic

#include <iostream>
using namespace std;

int main()
{
 int IntArray[10]; // array of int
 int  *pInt;        // pointer to int
 int i;            // loop counter

 // populate the int array with 1, 2, 3, ...
 for(i = 0; i < 10; i++)
 {
  IntArray[i] = i+1;
 }

 // store the address of the first element of IntArray 
 //in pointer
 pInt = IntArray;

 // print out values in the int array
 for (i = 0; i < 10; i++)
 {
  cout << *pInt << ' ' ;
  pInt++;      // pointer arithmetic
  // the above two lines could also be replaced with:
  // cout << *(pInt++) << ' ' ;
 }
 cout << endl;
 return 0;
}

Running session:

mercury[19]% CC PointerArith.cpp -LANG:std -o PointerArith
mercury[20]% PointerArith
1 2 3 4 5 6 7 8 9 10 
mercury[21]% 
 

4. Array of Pointers

Code Lising

// File name:  ~ftp/pub/class/cplusplus/PointerArray.cpp
// Purpose:    Demonstrates the use of array of pointers.

#include <iostream>
#include <stdio.h>
using namespace std;

int main()
{
 // initialize an array of char pointers with five fortunes
 const char* const Fortune[5] = 
          {" Earth is a great funhouse without the fun.",
    " There is always more hell that needs raising.",
    " Confession is good for the soul, but bad for the career.",
    " Live in a world of your own, but always welcome visitors.",
    " The man who laughs has not yet been told the terrible news."
    };
 cout << "Here are the 5 fortunes: " << endl;
 for(int i = 0; i < 5; i++)
 {
  cout << Fortune[i] << endl;
 }

 
}    

Running Session

mercury[121]% CC -LANG:std PointerArray.cpp -o PointerArray
mercury[122]% PointerArray
Here are the 5 fortunes: 
 Earth is a great funhouse without the fun.
 There is always more hell that needs raising.
 Confession is good for the soul, but bad for the career.
 Live in a world of your own, but always welcome visitors.
 The man who laughs has not yet been told the terrible news.
mercury[123]% 

 

 

Class and object 


Contents of this section:

  1. A simple program demonstrating C++ class
  2. Constructor
  3. Using inline initialization in constructor
  4. Copy constructor
  5. Destructor

1. A simple program demonstrating C++ class

    Code Listing: 

// File Name: ~ftp/pub/class/cplusplus/Class/SimpleClass.cpp
// Purpose:   Demonstrates the use of a simple C++ class

#include <iostream>
using namespace std;

class cl {
  int i; // private by default
public:
  int get_i();
  void put_i(int j);
};

int cl::get_i()
{
  return i;
}

void cl::put_i(int j)
{
  i = j;
}

int main()
{
  cl s;

  s.put_i(10);
  cout << s.get_i() <<endl;

  return 0;
}

    Running session:

 
@10:46am merc-hu[90]% CC -LANG:std SimpleClass.cpp -o SimpleClass
@10:46am merc-hu[91]% SimpleClass 
10
@10:46am merc-hu[92]% 

2. Constructor

Code listing:

// File Name: ~ftp/pub/class/cplusplus/Class/Constructor.cpp
// Purpose:   Demonstrates the use of constructor in a C++ class
// Author:    Ivor Horton, Beginning Visutal C++ 6

#include <iostream>
using namespace std;

// Class to represent a box
class Box
{
  public:
    double length;
    double breadth;
    double height;

    // Constructor
    Box(double lengthValue, double breadthValue, double heightValue)
    {
      cout << "Box constructor called" << endl;
      length = lengthValue;
      breadth = breadthValue;
      height = heightValue;
    }

    // Function to calculate the volume of a box
    double volume()
    {
      return length * breadth * height;
    }
};

Running session:

 
@11:12am merc-hu[115]% CC -LANG:std Constructor.cpp -o Constructor
@11:13am merc-hu[116]% Constructor
Box constructor called

Size of first Box object is 80 by 50 by 40
Volume of first Box object is 160000
@11:13am merc-hu[117]% 

3. Using inline initialization in constructor

    Code Listing: 

 
// File Name: ~ftp/pub/class/cplusplus/Class/Inline.cpp
// Purpose:   Demonstrates the use of initialization list in a constructor 
// Author:    Ivor Horton, Beginning Visutal C++ 6

#include <iostream>
using namespace std;

// Class to represent a box
class Box
{
  public:
    double length;
    double breadth;
    double height;

    // Inline initialization
    Box(double lv = 1.0, double bv = 1.0, double hv = 1.0):length(lv),
                                                           breadth(bv),
                                                           height(hv)
    {
      cout << "Box constructor called" << endl;
    }

    // Function to calculate the volume of a box
    double volume()
    {
      return length * breadth * height;
    }
};

int main()
{
  Box firstBox(80.0, 50.0, 40.0);

  // Calculate the volume of the box
  double firstBoxVolume = firstBox.volume();
  cout << endl;
  cout << "Size of first Box object is "
       << firstBox.length  << " by "
       << firstBox.breadth << " by "
 << firstBox.height
       << endl;
  cout << "Volume of first Box object is " << firstBoxVolume
       << endl;

  return 0;
}

    Running session:

@9:48am merc-hu[132]% CC -LANG:std Inline.cpp -o Inline
@9:49am merc-hu[133]% Inline
Box constructor called

Size of first Box object is 80 by 50 by 40
Volume of first Box object is 160000
@9:49am merc-hu[134]% 
��

4. Copy constructor 

    Code Listing: 

 
// File:    ~ftp/pub/class/cplusplus/Class/CopyCons.cpp
// Purpose: Demonstrate the use of copy constructor in C++

#include <iostream>
#include <cstdlib>
using namespace std;

class myclass {
  int *p;
public:
  myclass(int i);
  ~myclass();
  int getval() { return *p; }
};

myclass::myclass(int i)
{
  cout << "Allocating p\n";
  p = new int;
  if(!p) {
    cout << "Allocation failure.\n";
    exit(1); // exit program if out of memory
  }

  *p = i;
}

myclass::~myclass()
{
  cout << "Freeing p\n";
  delete p;
}

// when this function is called, the copy constructor is called
void display(myclass ob)
{
  cout << ob.getval() << '\n';
}

int main()
{
  myclass a(10);

  display(a);

  return 0;
}

    Running session:

@10:17am merc-hu[153]% CC -LANG:std Copycons.cpp -o Copycons
@10:18am merc-hu[154]% Copycons
Allocating p
10
Freeing p
Freeing p
@10:36am merc-hu[155]% 
��

5. Destructor 

    Code Listing: 

// File:    ~ftp/pub/class/cplusplus/Class/Destructor.cpp
// Purpose: Demonstrate the use of destructor in C++

#include <iostream>
#include <cstdlib>
using namespace std;

class myclass {
  int *p;
public:
  myclass(int i);
  ~myclass();
  int getval() { return *p; }
};

myclass::myclass(int i)
{
  cout << "Allocating p\n";
  p = new int;
  if(!p) {
    cout << "Allocation failure.\n";
    exit(1); // exit program if out of memory
  }

  *p = i;
}

// use destructor to free memory
myclass::~myclass()
{
  cout << "Freeing p\n";
  delete p;
}

void display(myclass &ob)
{
  cout << ob.getval() << '\n';
}
int main()
{
  myclass a(10);

  display(a);

  return 0;
}


 

    Running session:

@10:43am merc-hu[157]% CC -LANG:std Destructor.cpp -o Destructor
@10:44am merc-hu[158]% Destructor
Allocating p
10
Freeing p
@10:44am merc-hu[159]% 
 
 

No comments:

Post a Comment