|< C++ Data Encapsulation 4 | Main | C++ Data Encapsulation 6 >| Site Index | Download |


 

 

 

 

 

MODULE 13a

C++ OBJECTS & CLASSES - ENCAPSULATION PROGRAM EXAMPLES 5

 

 

 

 

 

 

My Training Period: xx hours

 

This is a continuation from the previous Module. The source code for this tutorial is available in C++ Data Encapsulation source codes.

 

The C++ programming abilities that must be covered in this session: Able to understand and use:

 

 

 

 

13.7  new and delete operators

  • These operators provide better dynamic memory allocation compared to malloc() and free() function calls used in C.  Consider the following code:

TypeName     *typeNamePtr;

  • In ANSI C (ISO/IEC C), to dynamically create an object of type TypeName, you would write like this:

typeNamePtr = malloc(sizeof(TypeName));

  • This requires a function call to malloc().  In C++ you simply write:

typeNamePtr = new TypeName;

  • The new operator automatically creates a class’s object of the proper size, calls the constructor for the object (if any) and returns a pointer of the correct type.  If there is unavailable space, 0 pointer is returned.

  • Next, to free the space for the allocated class’s object, after it has been used, the delete operator is used as follows:

delete     typeNamePtr;

  • An initializer also  is permitted for newly created object, for example:

double  *Ptr = new    double (4.2345);

  • This initializes a newly created double object to 4.2345.  Example for an array:

ObjectPtr = new int[10][10];

  • Then can be deleted by using:

delete[ ] ObjectPtr;

  • new and delete automatically invokes the constructor and destructor classes respectively.

13.8    An Object With A Pointer To Another Object

  • The program named oblist.cpp contains an object with internal reference to another object of its own class.  This is the standard structure used for a singly linked list and we will keep the use of it very simple in this program.

1.     // program oblist.cpp

2.     // object and list

3.      

4.     #include <iostream>

5.     using namespace std;

6.      

7.     // a class declaration part

8.     class wall

9.     {

10.        int    length;

11.        int    width;

12.        wall   *another_wall;    // a pointer variable

13.        public:

14.             wall(void);

15.             // a constructor declaration

16.             void   set(int new_length, int new_width);

17.             int    get_area(void);

18.             void   point_at_next(wall *where_to_point);

19.             wall  *get_next(void);

20.      };

21.      

22.      // a class implementation part

23.      wall::wall(void)

24.      // a constructor implementation

25.      {

26.             length = 8;

27.             width = 8;

28.             another_wall = NULL;

29.      }

30.     

31.      // this method will set a wall size to the input parameters

32.      void wall::set(int new_length, int new_width)

33.      {

34.             length = new_length;

35.             width = new_width;

36.      }

37.     

38.      // this method will calculate and return the area of a wall instance

39.      int wall::get_area(void)

40.      {

41.            return  (length * width);

42.      }

43.     

44.      // this method causes the pointer to point to the input parameter

45.      void wall::point_at_next(wall *where_to_point)

46.      {

47.             another_wall = where_to_point;

48.      }

49.     

50.      // this method returns the wall the current one points to

51.      wall *wall::get_next(void)

52.      {

53.             return  another_wall;

54.      }

55.      

56.      // main program

57.      void main()

58.      {

59.         wall small, medium, large;

60.         // objects are instantiated, of type class wall

61.         wall  *wall_pointer;

62.         // wall  *point;

63.         // a pointer to a wall

64.        

65.         small.set(5, 7);

66.         large.set(15, 20);

67.        

68.         // point = new wall;

69.         // use the defaults value supplied by the constructor

70.         cout<<"Using small.set(5, 7):\n";

71.         cout<<"----------------------\n";

72.         cout<<"Area of the small wall surface is "<<small.get_area()<<"\n\n";

73.         cout<<"Using default/constructor value\n";

74.         cout<<"-------------------------------\n";

75.         cout<<"Area of the medium wall surface is "<<medium.get_area()<<"\n\n";

76.         cout<<"Using large.set(15, 20):\n";

77.         cout<<"------------------------\n";

78.         cout<<"Area of the large wall surface is "<<large.get_area()<<"\n\n";

79.        

80.         small.point_at_next(&medium);

81.         medium.point_at_next(&large);

82.        

83.         wall_pointer = &small;

84.         wall_pointer = wall_pointer->get_next();

85.        

86.         cout<<"The wall’s pointer pointed to has area "<<wall_pointer

87.                                                      ->get_area()<<"\n";

88.        

89.         // system("pause");

90.  }

 

90 lines: Output:

 

C++ object and class output program examples - constructor and destructor

another_wall = NULL;

void    point_at_next(wall *where_to_point);

wall    *get_next(void);

wall *wall::get_next(void)

{

   return another_wall;

}

small.point_at_next(&medium);

medium.point_at_next(&large);

wall_pointer = &small;

wall_pointer = wall_pointer->get_next();

 

C++ object and class output program examples - link list and pointers

13.9  this Keyword

class_name   *this;

thisvariable_name

// using the this pointer explicitly

// to refer to object members

#include <iostream>

using namespace std;

 

class ThiPoint

{

      int c;

      public:

          ThiPoint(int);

          void display();

};

 

ThiPoint::ThiPoint(int a){ c = a;}  // just a constructor

 

void ThiPoint::display()

{

      cout<<"c         = "<<c<<endl;

      cout<<"this->c   = "<<this->c<<endl;

      cout<<"(*this).c = "<<(*this).c<<endl;

      // use parentheses for (*this).c because

      // dot has higher precedence than *

}

 

void main(void)

{

      ThiPoint b(10);

       b.display();

}

 

Output:

 

 

 

 

 

 

 

 

 

 

 

 

 

----------------------------------------------------------------------

 

C++ object and class output program examples - the this pointer

 

13.10    A Simple Link List Of Objects

1.     // program oblink.cpp,

2.     // an object link list

3.     #include <iostream>

4.     using namespace std;

5.      

6.     // class declaration part

7.     class wall

8.     {

9.          int length;

10.        int width;

11.        wall   *another_wall;    // a pointer variable

12.        public:

13.             wall(void);

14.             // a constructor declaration

15.             void   set(int new_length, int new_width);

16.             int    get_area(void);

17.             void   point_at_next(wall *where_to_point);

18.             wall  *get_next(void);

19.      };

20.     

21.      // a class implementation part

22.      wall::wall(void)

23.      // constructor implementation

24.      {

25.             length = 8;

26.             width = 8;

27.             another_wall = NULL;

28.      }

29.     

30.      // this method will set a wall size to the input parameters

31.      void wall::set(int new_length, int new_width)

32.      {

33.             length = new_length;

34.             width = new_width;

35.      }

36.     

37.      // this method will calculate and return the area of a wall instance

38.      int wall::get_area(void)

39.      {

40.            return  (length * width);

41.      }

42.      

43.      // this method causes the pointer to point to the input parameter

44.      void wall::point_at_next(wall *where_to_point)

45.      {

46.             another_wall = where_to_point;

47.      }

48.     

49.      // this method returns the wall the current one points to

50.      wall *wall::get_next(void)

51.      {

52.             return  another_wall;

53.      }

54.     

55.      // main program

56.      void main()

57.      {

58.          wall *start = NULL;       // always point to the start of the list

59.          wall *temp = NULL;      // working pointer, initialize with NULL

60.          wall *wall_pointer;        // use for object wall instances

61.          

62.          // generate the list

63.          for(int index = 0; index < 8; index++)

64.          {

65.              wall_pointer = new wall;     // a new object instances

66.              wall_pointer->set(index+1, index+3);

67.              

68.              if(start == NULL)

69.                 start = wall_pointer;    // first element in list

70.              else

71.                 temp->point_at_next(wall_pointer); // next element, link list

72.              

73.               temp = wall_pointer;

74.               // print the list

75.               cout<<"Starting with wall_pointer

76.                               ->set("<<(index+1)<<","<<(index+3)<<")"<<"\n";

77.               cout<<"       New Wall's surface area is " <<temp->get_area() << "\n";

78.          }

79.          

80.           // clean up

81.           temp = start;

82.           do {

83.                     temp = temp->get_next();

84.                     delete   start;

85.                     start = temp;

86.                 } while (temp != NULL);

87.          

88.           // system("pause");

89.     }

 

89 lines: Output:

 

C++ object and class link list program output examples

 

  • You will recall that in the last program the only way we had to set or use the embedded pointer was through the use of  two methods named point_at_next() and  get_next() which are listed in lines 17 and 18 of this program.

void   point_at_next(wall *where_to_point);

wall  *get_next(void);

  • We will use these to build up our linked list then traverse and print the list.  Finally, we will delete the entire list to free the space on the heap.

  • In lines 58 through 60 as in the following code segment, we define three pointers for use in the program as shown below.  The pointer named start will always point to the beginning of the list, but temp will move down through the list as we creating it.

    wall *start = NULL;         // always point to the start of the list

    wall *temp = NULL;        // working pointer, initialize with NULL

    wall *wall_pointer;          // use for object wall instances

 

for(int index = 0; index < 8; index++)

{

       wall_pointer = new wall;     // new object instances

       wall_pointer->set(index+1, index+3);

       ...

       ...

 }

temp = start;

     do{

               temp = temp->get_next();

               delete   start;

               start = temp;

       } while (temp != NULL);

13.11    Nesting Objects

   mail_info   label;

 

C++ object and class nesting the objects program output examples

label.set(ship, post);

1.            // program obnest.cpp

2.            #include <iostream>

3.            using namespace std;

4.             

5.            // first class declaration

6.            class mail_info

7.            {

8.                int   shipper;

9.                int   postage;

10.             public:

11.                 void set(int input_class, int input_postage)

12.                 {

13.                     shipper = input_class;

14.                     postage = input_postage;

15.                 }

16.                 int get_postage(void)

17.                 { return postage;}

18.             };

19.             

20.             // a second class declaration

21.             class box

22.             {

23.                 int   length;

24.                 int   width;

25.                 mail_info   label;

26.                 

27.                 public:

28.                     void set(int l, int w, int ship, int post)

29.                     {

30.                         length = l;

31.                         width = w;

32.                         label.set(ship, post);

33.                         // accessing the first class, mail_info set() method

34.                     }

35.             

36.              int get_area(void) { return (length * width);}

37.             };

38.             

39.             // main program

40.             void main()

41.             {

42.                 box      small, medium, large;   // object instances

43.             

44.             small.set(2,4,1,35);

45.             medium.set(5,6,2,72);

46.             large.set(8,10,4,98);

47.             

48.             cout<<"Normal class-->small.get_area()\n";

49.             cout<<"-------------------------------\n";

50.             cout<<"Area of small box surface is "<<small.get_area()<< "\n\n";

51.             cout<<"Normal class-->medium.get_area()\n";

52.             cout<<"-------------------------------\n";

53.             cout<<"Area of medium box surface is "<<medium.get_area() << "\n\n";

54.             cout<<"Normal class-->large.get_area()\n";

55.             cout<<"-------------------------------\n";

56.             cout<<"Area of large box surface is "<<large.get_area()<<"\n\n";

57.             

58.             // system("pause");

59.         }

 

59 lines: Output:

 

C++ object and class program output samples and examples

tenouk C++ object oriented tutorial: encapsulation code samples

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Further related C++ reading and digging:

 

  1. The source code for this tutorial is available in C++ Data Encapsulation source codes.
  2. Any reference to Data Structures Using C.
  3. Check the best selling C / C++ and object oriented books at Amazon.com.
  4. MFC library class hierarchy chart.

 

 

 

 

 

 

 

|< C++ Data Encapsulation 4 | Main | C++ Data Encapsulation 6 >| Site Index | Download |


C++ Class and Object - The Encapsulation and Data Abstraction:  Part 1 | Part 2 | Part 3 | Part 4