Objects in Problem Solutions

 

Click to visit each subsection.

5.4.1

5.4.2

5.4.3

5.4.4

5.4.5

5.4.6

5.4.7

Quiz

 

5.4.2 Explain the basic features and advantages of encapsulation

 

 

5.4.1 Outline the features of an object

 

An object is generally a combination of both data and operations that can be performed in association with the data.  An object can be compared to a black box, which only receives and sends messages because the user should never need to look into the box.  Objects are meant to be private and should only be accessed through functions inside the object.  An object usually consists of several fields: data members, which is the actual data, member functions, the construction and destruction of the object itself, operations that set or return the data members, operations that are usually unique to the specific data type in the object, and any other operation used within the object.

 

5.4.2 Explain the basic features and advantages of encapsulation

 

Encapsulation allows the programmer to design effectively at a high level of abstraction.  The basic features of encapsulation is to create an absolute barrier between interface and implementation.  Implementation is to be hidden and not changed, instead having the interface adjust to the implementation.  There are several advantages to this, first, information cannot be changed in the implementation from the user, which will eliminate any problems in that area.  Also, data cannot be accessed without member functions, thus information can be kept private in an object.  Lastly, when designing an object for a particular program, if implementation is kept constant through encapsulation, there are less bug fixes and coding if implementation is changed every time it is used in another program.

 

5.4.3 Explain the basic features and advantages of information and data hiding

 

Once encapsulated, data members as well as details of implementation are hidden from the client of the object.  There are several advantages to doing this, as the programmer can control data movement in the object, so that the user may not access private data members without proper accessing functions.  Also, because implementation of the object is no longer an area of concern, the programmer can now work at a more abstract level, simplifying programming a lot more.

 

5.4.4 Explain the basic features and advantages of polymorphism

 

Polymorphism is described as the ability of different object to respond, in an appropriate way, to an identical operation.  The main benefit of polymorphism is that it simplifies the programming interface or use.  It creates a “template” object that can be reused class after class instead of creating a new name functions or data members of a certain type.  Functions are created generically to handle most data types.  Also, a function name can be overloaded to denote many different functions, and a template can be used as a pattern for many classes.

 

5.4.5 Explain the basic features and advantages of inheritance

 

Inheritance allows one object to be derived from another.  The new object has all the data members and member functions of the one it is derived from, as well as any other data or functions the programmer wishes to insert.  Although data from the original object is copied into the derived object, the programmer can change already made functions into new ones for the derived object.  The advantage of inheritance is that the programmer does not need to totally rewrite an object, which can be very extraneous and redundant, but instead access data and member functions from an object to incorporate into a new object.  Deriving a new object from a previously made object generally saves a lot of time and coding.

 

5.4.6 Trace an algorithm that includes objects

 

/*==============================================================================

 

    Program:  Interface file of the artCLASS class

 

    Author:   Gerry Donaldson

 

    Purpose:  Interface of the artCLASS class.

 

    Source File:  artclass.h

 

    Language:  Dev-C++ using the MinGW (Minimalist GNU for Windows) compiler

    Target:    Real Mode Application (DOS)

    System:    AMD Athlon, 1100 MHz Running Under Windows 2000

 

    This Revision:  June 7, 2001

 

==============================================================================*/

 

#include <iostream.h>

#include <fstream.h>

#include <assert.h>

#include <conio.h>

// #include <bool.h>  // comment out bool.h when compiler supports bool data type

#include "apstring.h"

 

typedef struct AuthorNODE* ptrType;  // pointer to node of type AuthorNODE

 

struct AuthorNODE

{

   apstring  firstName;

   apstring  surName;

        int  birthYear;

   apstring  city;

   apstring  lang;

    ptrType  next;

};                     // end struct

 

class artCLASS

{

  private:

    ////////////////////////////////////////////////////////////////////////////

    //

    //              ONLY DECLARE A POINTER ONCE IN A CLASS

    //

    // Ddeclarations of all auxiliary pointers, IN ALL CASES, upon completion of

    // execution of the function member(s) in which they are invoked, point to

    // NULL or a node in the linked list.  When any function member terminates,

    // ALL NODES POINTED TO BY AUXILIARY POINTERS ARE ALSO IN THE LINKED LIST.

    // It is therefore unnecessary to delete auxiiliary nodes after ALL nodes in

    // a linked list are deleted.  All nodes in the linked list of this class,

    // artCLASS, are deleted when the destructor, ~artCLASS, is executed.

    //

    // Auxiliary pointers are declared here and not in function members because

    // they are IMPLICIT PARAMETERS:  global within the class so that they are

    // declared for all member functions of the class once they are declared

    // anywhere within the class.  Delcaring them here, ONCE AND FOR ALL, avoids

    // the risk of duplicate declarations when a member function is executed.

    //

    ////////////////////////////////////////////////////////////////////////////

 

    ptrType myHead, myNewNode, myTail, myPrev, myCur;

 

  public:

  // Constructors and destructors:

    artCLASS();

    ~artCLASS();

 

    void getAndInsertNewNode();

             void getNodeFromFile();

             void printLinkedList();

    void deleteNode();

             void deleteList();

    void displaySelectedNode();

    void writeListToFile();

};  // end artCLASS

 

void error();

 

 

 

/*==============================================================================

 

    Program:  Implementation file of the artCLASS class.

 

    Author:   Gerry Donaldson

 

    Purpose:  Implements functions in the artCLASS class.

 

    Source File:  artclass.cpp

 

    Language:  Dev-C++ using the MinGW (Minimalist GNU for Windows) compiler

    Target:    Real Mode Application (DOS)

    System:    AMD Athlon, 1100 MHz Running Under Windows 2000

 

    This Revision:  June 7, 2001

 

==============================================================================*/

 

#include "artCLASS.h"

#include <cstdlib>

 

void error()

{

  clrscr();

  cerr << "Incorrect choice" << endl;

  cout << "Press any key to return to the menu.";

 

  getche();  // system("PAUSE");  //  getch();

 

}

 

artCLASS::artCLASS()

{

   clrscr();

   cout << "Constructor stub:  This allocates memory for this class.\n";

 

            ifstream in_file( "author.dat", ios::in);

 

   if ( !in_file ) {

            cerr << "File could not be opened."  << endl;

    myHead = NULL;  // initialize myHead

   } // end if   see Deitel & Deitel, page 723 for this loop

 

   else {

            if ( !in_file.eof() )

               {

         myHead = new AuthorNODE;

                        in_file >> myHead->firstName >> myHead->surName

                             >> myHead->birthYear >> myHead->city >> myHead->lang;

               myHead->next = NULL;

                  myTail = myHead;

                  while ( !in_file.eof() ){

                     myTail->next = new AuthorNODE;

                     myTail = myTail->next;

                     in_file >> myTail->firstName >> myTail->surName

                                >> myTail->birthYear >> myTail->city >> myTail->lang;

                           myTail->next = NULL;

                  } // end while

               } // end if !in_file.eof()

   } // end else

 

            in_file.close();

 

            cout << "Press ENTER to continue!";

   getche(); // system("PAUSE");  //  getch();

}

 

artCLASS::~artCLASS()  // Called automatically when programme terminates.

{

   clrscr();

   cout << "Destructor stub:  This returns allocated memory to the heap.\n";

   myCur = myHead;

            while (myCur != NULL)   // ie:  while list is not empty

   {

      myHead = myHead->next;

      delete myCur;

      myCur = myHead;

   }  // end while

 

   // Clean up memory and release back to the heap

            delete myHead;

 

   cout << "Press ENTER to finish!";

   getche(); // system("PAUSE");  //  getch();

}

 

void artCLASS::getAndInsertNewNode()

{

   myNewNode = new AuthorNODE;

   cout << endl << endl;

   cout << "First name: ";        cin >> myNewNode->firstName;

   cout << "Surname: ";           cin >> myNewNode->surName;

   cout << "Year of birth: ";     cin >> myNewNode->birthYear;

   cout << "City of birth: ";             cin >> myNewNode->city;

   cout << "Language designed: "; cin >> myNewNode->lang;

 

   //  myNewNode becomes new head of the list and myHead becomes the second node.

   if ( (myHead == NULL) || (myNewNode->birthYear < myHead->birthYear) )

   {

            myNewNode->next = myHead;

      myHead = myNewNode;

   }   // end if where the new node became the head

   else{     // where the new node is inserted AFTER the head

 

            // Initialize myPrev & myCur to start traversal from the beginning of the list.

                        myPrev = new AuthorNODE;

                        myPrev = NULL;

                        myCur = myHead;

 

      // Advance myPrev and myCur until (myCur->birthYear >= myNewNode->birthYear).

            while ( (myCur != NULL) && (myCur->birthYear < myNewNode->birthYear ) )

            {

                        myPrev = myCur;

                        myCur = myCur->next;

                        }  // end while myCur != NULL

 

               // Insert myNewNode AFTER the first node of the list.

                        myNewNode->next = myPrev->next;

            myPrev->next = myNewNode;

   } // end else where the new node is inserted AFTER the head

} // end getAndInsertNewNode()

 

 

void artCLASS::getNodeFromFile()

{

            ifstream in_file( "newnode.dat", ios::in);

 

   if ( !in_file ) {       // if in_file did not exist

            cerr << "File could not be opened."  << endl;

   }                       // end if in_file did not exist

   else {         // in_file does exist so read fields of records into the node

      myNewNode = new AuthorNODE;

                        in_file >> myNewNode->firstName >> myNewNode->surName

              >> myNewNode->birthYear >> myNewNode->city >> myNewNode->lang;

                        in_file.close();

 

               //  myNewNode becomes new head of the list and myHead becomes the second node.

            if ( (myHead == NULL) || (myNewNode->birthYear <= myHead->birthYear) )

                        {

            myNewNode->next = myHead;

      myHead = myNewNode;

                           }   // end if where the new node became the head

            else{     // where the new node is inserted AFTER the head

 

                        // Initialize myPrev & myCur to start traversal from the beginning of the list.

                                    myPrev = new AuthorNODE;

         myPrev = NULL;

                                    myCur = myHead;

 

            // Advance myPrev and myCur until (myCur->birthYear < myNewNode->-birthYear).

                        while ( (myCur != NULL) && (myCur->birthYear < myNewNode->birthYear ) )

                        {

                                    myPrev = myCur;

                                    myCur = myCur->next;

                                    }  // end while myCur != NULL

 

                        // Insert myNewNode AFTER the first node of the list.

                                    myNewNode->next = myPrev->next;

                        myPrev->next = myNewNode;

            } // end else where the new node is inserted AFTER the head

 

   } // end else >> reading fields of records into the node

} // artCLASS::getNodeFromFile()

 

 

void artCLASS::deleteNode()

{

 

   clrscr();

   // print out list

 

   if ( myHead == NULL ) {

                        cout << "There are no records in the list.\n\n";

         cout << "Press ENTER to return to the main menu.";

            } // end if myHead == NULL

   else {

      int i = 0;

            for (myCur = myHead; myCur != NULL; myCur = myCur->next)

            { i++;

       cout << i << ' ' << myCur->firstName << ' ' << myCur->surName << ' '

            << myCur->birthYear << ' ' << myCur->city << ' ' << myCur->lang << endl;

            } // end for

 

                        int choice;

      do{

                                    cout << endl << "Type the number of the record you want deleted "

                                  << "and press the enter key:";

                                    cin >> choice;

 

         if ( (choice<1) || (choice>i) )

            cout << "Choice must a number on the screen.  Try again.\n";

 

        } while ( (choice < 1) || (choice > i) );

 

            // traversal locates node to be deleted

               myPrev = NULL; i = 1;

            for (myCur = myHead; i < choice; ++i, myPrev = myCur, myCur = myCur->next);

 

                        if ( myCur == myHead ) // test if head is node to be deleted

              {

                          myHead = myHead->next;

                 delete myCur;

                 }  // end if myCur == myHead

                        else           // do this if node other than head is to be deleted

               {

       myPrev->next = myCur->next;

       myCur->next = NULL;

             delete myCur;

      }  // end else myCur == myHead

   } // end else myHead == NULL

}  // end deleteNode()

 

void artCLASS::deleteList()

{

   myCur = myHead;

            while (myCur != NULL)   // ie:  while list is not empty

   {

      myHead = myHead->next;

      delete myCur;

      myCur = myHead;

   }  // end while

 

   myHead = NULL;

 

} // end deleteList()

 

void artCLASS::displaySelectedNode()

{

   clrscr();

   // print out list

 

   if ( myHead == NULL ) {

                        cout << "There are no records in the list.\n\n";

         cout << "Press ENTER to return to the main menu.";

            } // end if myHead == NULL

   else {

            cout << endl;

   apstring firstNameTarget, surNameTarget;

   cout << "Please enter first name of author to display: ";

   cin >> firstNameTarget;

   cout << "Please enter last name of author to display: ";

   cin >> surNameTarget;

            cout << endl;

 

            myCur = myHead;

 

            while ( (            myCur != NULL                    ) &&

                          ( (myCur->firstName != firstNameTarget ) ||

             ( myCur->surName   != surNameTarget   ) )   )

            myCur = myCur->next;  // traversal until target found or end of loop

               if ( myCur == NULL )  // traversal reached end of list without finding target

                        cout << "A record with BOTH of those names is not in the list.\n\n";

      else

            cout << myCur->firstName << ' ' << myCur->surName << ' '

           << myCur->birthYear << ' ' << myCur->city    << ' '

           << myCur->lang << endl << endl;

            } // else

   cout << "Press ENTER to return to main menu.";

   getche(); // system("PAUSE");  //  getch();

} // end artCLASS::displaySelectedNode()

 

 

void artCLASS::printLinkedList()

{

   cout << endl << endl;

 

   if ( myHead == NULL )

                        cout << "There are no records in the list.\n\n";

   else{

                         for (myCur = myHead; myCur != NULL; myCur = myCur->next)

                          cout << myCur->firstName << ' ' << myCur->surName << ' '

                << myCur->birthYear << ' ' << myCur->city << ' ' << myCur->lang

                << endl << endl;

            } // end else

 

   cout << "Press ENTER to return to the menu.";

   char ch = getche(); // system("PAUSE");  //  getch();

}  // printLinkedList()

 

void artCLASS::writeListToFile()

{

            ofstream out_file( "auth_add.dat", ios::out);

 

   if ( !out_file ) {       // if out_file does not exist

            cerr << "File could not be opened."  << endl;

   }                       // end if in_file did not exist

   else {  // out_file does exist so write linked list to the file

 

               // All apstring variables must be converted to arrays of char that

            // terminate in a null char \0  The c-str() does this conversion.

 

              apstring nextName;

 

            for (myCur = myHead; myCur != NULL; myCur = myCur->next)

                        out_file << myCur->firstName.c_str() << ' ' << myCur->surName.c_str()

           << ' ' << myCur->birthYear<< ' ' << myCur->city.c_str()

           << ' ' << myCur->lang.c_str() << endl << endl;

        } // end where out_file existed so linked list was written to the file

            out_file.close();

 

   cout << "The linked list has been written to \"auth_add.dat\".\n\n";

 

   cout << "Press ENTER to return to the main menu.";

   getche(); // system("PAUSE");  //  getch();

} //end artCLASS::writeListToFile()

 

 

 

5.4.7 Discuss the advantages and disadvantages of using objects in problem solutions

The advantages of using objects in problem solutions is the ability of the object for encapsulation, information and data hiding, polymorphism and inheritance.  The individual advantages of each are highlighted in the sections before.  There are disadvantages to using objects as well.  Objects require more time then other programming solutions, thus for simpler programs, objects waste time and do not provide significant advantages.  Also, because information and data hiding is usually implemented with objects, clients can not easily correct any errors within object libraries, even if they are simple.  Because information is usually hidden, efficiency is also hidden, thus the client does not know the efficiency of the program for optimal use.  Lastly, many languages do not currently support objects and there is no current standard to write objects, thus very ambiguous because objects are usually language specific.

 

Quiz

 

1.       It is possible to access data members of an object through any function        A: F

2.       It is quicker to solve a problem with objects                                                A: F

3.       All programming languages can handle objects                                             A: F

4.       Creating a generic object able to handle many types is polymorphism           A: T

5.       To inherit means to take programmer chosen functions from another object  A: F

6.       A disadvantage of using objects is that efficiency is hidden               A: T

7.       By using objects, programmers work at a more abstract level                      A: T

8.       Encapsulation is to create a barrier between interface and implementation     A: T

9.       Polymorphism allows for data hiding                                                            A: F

10.    There are standard procedures of constructing an object                              A: F

 

11.    What things are generally found in an object?

A: Constructor, Destructor, accessors, modifiers, functions that access or edit data in the object.

 

12.    What are the advantages of encapsulation?

A: Data output can be controlled by programmer, so that user cannot access data easily; less bug fixes and coding if interface adjusts to implementation instead of vice-versa.

 

13.    What are the advantages of information and data hiding?

A: Programmer can control data movement, so that user of program cannot access data; useful when data needs to be secure, such as personal information.  Also, allows user to work at a more abstract level, meaning it is a lot easier for the programmer to construct code.

 

14.    What are the advantages of polymorphism?

A: Less coding therefore saving time.

 

15.    What are the advantages of inheritance?

A: Less coding and therefore saves time.

 

 

References:

 

http://www.ib-computing.com

 

http://objectdiscovery.com/