Docstoc

c

Document Sample
c Powered By Docstoc
					A simple program demonstrating C++ class
                                 Code Listing:

 // 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:

 // Purpose:    Demonstrates the use of constructor in a C++ class

 #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



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

#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:


 // 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]%


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
 @11:12am merc-hu[37]%




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.
 @9:41am merc-hu[84]%




Create an abstract class.




#include <iostream>
using namespace std;

class area {
   double dim1, dim2;
public:
   void setarea(double d1, double d2)
   {
     dim1 = d1;
     dim2 = d2;
   }
   void getdim(double &d1, double &d2)
   {
     d1 = dim1;
     d2 = dim2;
   }
   virtual double getarea() = 0; // pure virtual function
};

class rectangle : public area {
public:
  double getarea()
  {
         double d1, d2;

         getdim(d1, d2);
         return d1 * d2;
     }
};

class triangle : public area {
public:
  double getarea()
  {
    double d1, d2;

         getdim(d1, d2);
         return 0.5 * d1 * d2;
     }
};

int main()
{
  area *p;
  rectangle r;
  triangle t;

     r.setarea(3.3, 4.5);
     t.setarea(4.0, 5.0);

     p = &r;
     cout << "Rectangle has area: " << p->getarea() << '\n';

     p = &t;
     cout << "Triangle has area: " << p->getarea() << '\n';

     return 0;
}




Demonstrate virtual functons: list interface




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

class list {
public:
     list *head;             //   pointer to start of list
     list *tail;             //   pointer to end of list
     list *next;             //   pointer to next item
     int num;                //   value to be stored

     list() {
        head = tail = next = NULL;
     }
     virtual void store(int i) = 0;
     virtual int retrieve() = 0;
};

class queue : public list {
public:
   void store(int i);
   int retrieve();
};

void queue::store(int i)
{
  list *item;

     item = new queue;
     if(!item) {
       cout << "Allocation error.\n";
       exit(1);
     }
     item->num = i;

     if(tail)
        tail->next = item;
     tail = item;
     item->next = NULL;
     if(!head)
        head = tail;
}

int queue::retrieve()
{
  int i;
  list *p;

     if(!head) {
       cout << "List empty.\n";
       return 0;
     }

     // remove from start of list
     i = head->num;
     p = head;
     head = head->next;
     delete p;

     return i;
}
class stack : public list {
public:
   void store(int i);
   int retrieve();
};

void stack::store(int i)
{
  list *item;

    item = new stack;
    if(!item) {
      cout << "Allocation error.\n";
      exit(1);
    }
    item->num = i;

    if(head)
       item->next = head;
    head = item;
    if(!tail)
       tail = head;
}

int stack::retrieve()
{
  int i;
  list *p;

    if(!head) {
      cout << "List empty.\n";
      return 0;
    }

    // remove from start of list
    i = head->num;
    p = head;
    head = head->next;
    delete p;

    return i;
}

int main()
{
  list *p;

    // demonstrate queue
    queue q_ob;
    p = &q_ob; // point to queue

    p->store(1);
    p->store(2);
    p->store(3);

    cout << "Queue: ";
    cout << p->retrieve();
    cout << p->retrieve();
    cout << p->retrieve();

    cout << '\n';

    // demonstrate stack
    stack s_ob;
    p = &s_ob; // point to stack

    p->store(1);
    p->store(2);
    p->store(3);

    cout   <<   "Stack: ";
    cout   <<   p->retrieve();
    cout   <<   p->retrieve();
    cout   <<   p->retrieve();

    cout << '\n';

    return 0;
}




POLYMORPHISM

// dynamic allocation and polymorphism
#include <iostream>
using namespace std;

class CPolygon {
  protected:
     int width, height;
  public:
     void set_values (int a, int b)
       { width=a; height=b; }
     virtual int area (void) =0;
     void printarea (void)
       { cout << this->area() << endl; }
  };

class CRectangle: public CPolygon {
  public:
     int area (void)
       { return (width * height); }
  };

class CTriangle: public CPolygon {
  public:
     int area (void)
       { return (width * height / 2); }
  };

int main () {
  CPolygon * ppoly1 = new CRectangle;
  CPolygon * ppoly2 = new CTriangle;
  ppoly1->set_values (4,5);
  ppoly2->set_values (4,5);
  ppoly1->printarea();
  ppoly2->printarea();
  delete ppoly1;
  delete ppoly2;
  return 0;
}




Templates
Function templates

create a template function that returns the greater one of two objects




// function template
#include <iostream>
using namespace std;

template <class T>
T GetMax (T a, T b) {
  T result;
  result = (a>b)? a : b;
  return (result);
}

int main () {
  int i=5, j=6, k;
  long l=10, m=5, n;
  k=GetMax<int>(i,j);
  n=GetMax<long>(l,m);
  cout << k << endl;
  cout << n << endl;
  return 0;
}




Class templates
// class templates
#include <iostream>
using namespace std;

template <class T>
class mypair {
     T a, b;
   public:
     mypair (T first, T second)
       {a=first; b=second;}
     T getmax ();
};

template <class T>
T mypair<T>::getmax ()
{
  T retval;
  retval = a>b? a : b;
  return retval;
}

int main () {
  mypair <int> myobject (100, 75);
  cout << myobject.getmax();
  return 0;
}



Generic sum method




#include <iostream>
using namespace std;

template <class X> X sum(X *data, int size)
{
  int i;
  X result = 0;

    for(i = 0; i <size; i++) result += data[ i ];

    return result;
}

int main()
{
  int i[] = {1, 2, 3, 4};
  double d[] = {1.1, 2.2, 3.3, 4.4};
    cout << sum(i, 4) << endl;
    cout << sum(d, 4) << endl;

    return 0;
}



Object array: polymorphism.




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

class TwoDimensionShape {
  double width;
  double height;
  char name[20];
public:

    TwoDimensionShape() {
      width = height = 0.0;
      strcpy(name, "unknown");
    }

    TwoDimensionShape(double w, double h, char *n) {
      width = w;
      height = h;
      strcpy(name, n);
     }

     TwoDimensionShape(double x, char *n) {
       width = height = x;
       strcpy(name, n);
     }

     void showDim() {
       cout << "Width and height are " << width << " and " << height << endl;
     }

     double getWidth() {
        return width;
     }
     double getHeight() {
        return height;
     }
     void setWidth(double w) {
        width = w;
     }
     void setHeight(double h) {
        height = h;
     }
     char *getName() {
        return name;
     }

     virtual double area() {
       cout << "Error: area() must be overridden.\n";
       return 0.0;
     }

};

class Triangle : public TwoDimensionShape {
  char style[20]; // now private
public:

     Triangle() {
       strcpy(style, "unknown");
     }

     Triangle(char *str, double w,
              double h) : TwoDimensionShape(w, h, "triangle") {
       strcpy(style, str);
     }

     Triangle(double x) : TwoDimensionShape(x, "triangle") {
       strcpy(style, "isosceles");
     }

     double area() {
       return getWidth() * getHeight() / 2;
     }

     void showStyle() {
         cout << "Triangle is " << style << endl;
     }
};

class Rectangle : public TwoDimensionShape {
public:


     Rectangle(double w, double h) : TwoDimensionShape(w, h, "rectangle") { }


     Rectangle(double x) :
       TwoDimensionShape(x, "rectangle") { }

     bool isSquare() {
       if(getWidth() == getHeight())
          return true;
       return false;
     }

     // This is another override of area().
     double area() {
       return getWidth() * getHeight();
     }
};

int main() {

     TwoDimensionShape *shapes[5];

     shapes[0]   =   &Triangle("right", 8.0, 12.0);
     shapes[1]   =   &Rectangle(10);
     shapes[2]   =   &Rectangle(10, 4);
     shapes[3]   =   &Triangle(7.0);
     shapes[4]   =   &TwoDimensionShape(10, 20, "generic");

     for(int i = 0; i < 5; i++) {
       cout << "object is " << shapes[i]->getName() << endl;

         cout << "Area is " << shapes[i]->area() << endl;

         cout << endl;
     }

     return 0;
}

				
DOCUMENT INFO
Shared By:
Tags:
Stats:
views:8
posted:1/25/2011
language:English
pages:22