CS 118 OOP Lab Manual

  • Upload
    tik-tok

  • View
    456

  • Download
    28

Embed Size (px)

DESCRIPTION

CS 118 OOP Lab Manual

Citation preview

  • 1 | P a g e

    CS118 Lab Manual Fall 2012

    Yarmouk University Faculty of Information Technology and CS

    Computer Science Department

    CS 118: Object Oriented Programming lab Fall Semester: 2012 / 2013

    Prepared by:

  • 2 | P a g e

    CS118 Lab Manual Fall 2012

    Table of Contents:

    Preface : Page 3

    Coverage: Page 3

    Lab 1: - Introduction to Classes and Objects Page 4

    Lab 2: - Separating class Interface from its Implementation Page 6

    Lab 3: - Using different handles to access class members.

    - Writing and using destructors. Page 9

    Lab 4: - Principle of least privilege using const (constant) objects

    and const member functions.

    - Composition.

    Page 15

    Lab 5: - Composition.

    - Copy Constructor.

    - Friend functions.

    Page 20

    Lab 6: - Friend function & friend class.

    - Create and destroy objects dynamically.

    - Static data members and member functions.

    Page 24

    Lab 7: - Operator overloading. Page 28

    Lab 8: - Inheritance & Polymorphism Page 32

    Quizzes Description

    Page 37

  • 3 | P a g e

    CS118 Lab Manual Fall 2012

    Preface

    This lab manual supplements the teaching materials in the object oriented C++ programming language. The exercises here were based on the instructors class materials in cs117 course.

    Coverage

    This lab covers the following concepts in object oriented programming: Data abstraction, Encapsulation, Information Hiding, dynamic memory allocation, friend functions, Operator overloading, inheritance, and polymorphism.

  • 4 | P a g e

    CS118 Lab Manual Fall 2012

    Task #1: Introduction to Classes and Objects Objectives:

    The laboratory exercises basic C++ programming skills.

    The laboratory guides the students through the creation of a win32 console application project with C++ source file that uses Visual Studio Environment.

    The laboratory explores the fundamental concepts of a class such as

    public, private members, and constructors.

    Student Learning Outcomes:

    You will:

    Be able to select appropriate C++ programming language commands and constructs to write the code.

    Be able to develop executable computer programs using class.

    These outcomes will be achieved by means of lecture notes, learn-by-doing style in-class programming exercises.

    Background: Students have knowledge about the basic concept of class and object [data members, member function, and constructors].

  • 5 | P a g e

    CS118 Lab Manual Fall 2012

    LIST OF Exercises:-

    Exercise #1: Create an empty project to write a simple program to print your name. Exercise #2:

    Write a class implementation named (Display1) with: A single public member function named Print to print your name then use it. Exercise #3:

    Write a class implementation named (Display2) with: A single public member function named Print with one parameter to print any given string then use it.

    Exercise #4: Write a class implementation named (Display3) with: 1. A private data member NAME of type string.

    2. A public member function to set the value for NAME. 3. A public member function to get the value for NAME.

    4. A public member function named Print to print the value of data member NAME.

  • 6 | P a g e

    CS118 Lab Manual Fall 2012

    Task #2: Separating class Interface from Implementation

    Objectives:

    Separating class Interface from its Implementation for reusability.

    Defining default constructors and constructors with arguments.

    Student Learning Outcomes:

    You will: Be able to write a full documented and separated interface C++

    program that deal with classes. Be able to write a suitable constructor for a given class.

    Background:

    Students have knowledge about the basic concept of class and object [data members, member function, and constructors] as well as how to separate

    class interface from its implementation.

    Assumptions:

    All displays that your application produces are informative and reflect

    what the user is expected to do and in what order this should be done.

    Use the #ifndef.. #endif construct to make sure the header file is not included more than once.

  • 7 | P a g e

    CS118 Lab Manual Fall 2012

    LIST OF Exercises:-

    Exercise #1: Write a class that represents a book. Make sure that your program separate interface from implementation of this class.

    Data that is associated with Book class: o Title. o Author. o Publisher.

    Functions that can be performed on Book class:

    o SetAll function: set all data member values. o Get functions to retrieve ISBN and author name value for a given

    book. o Member function to print a summary of information for a given book.

    o Constructor to initialize object data members. o Constructor with arguments to initialize object data members for any value.

    Write a driver program that test Book class as follow:

    o Define a main function with an object (named b1). o Try to change the values stored on b1 using the SetAll function.

    o Print a summary of information for this object.

  • 8 | P a g e

    CS118 Lab Manual Fall 2012

    Exercise #2:

    Write a C++ program that uses a class that maintains a collection of employees. Make sure that your program separate interface from implementation of the Employee class.

    Data that is associated with an Employee class: o Employee ID. o Age (between 25-50). o Salary per month.

    Functions that can be performed on Employee class:

    o Constructor: (constructor with arguments). o AnnualSalary: Compute annual Salary.

    o SetAge: function that set and validates the value of employee age. o SetSalary: function that set and validates the value of employee

    Salary. o Print function that displays all data members of the class.

    Write a driver program that test Employee class as follow: o Create an object of type Employee using argument constructor. o Modify the value of salary for this object to be 1000$. o Compute the annual salary fort this object,

    o Display the values of this object.

  • 9 | P a g e

    CS118 Lab Manual Fall 2012

    Task #3: Using different handles to access class members. Writing and using destructors.

    Objectives:

    Understand class scope and accessing class members via the name of an object, a reference to an object or a pointer to an object.

    Writing and using destructors to perform "termination housekeeping"

    on an object before it is destroyed. Declaring local, global, and static local objects.

    Learn when constructors and destructors are called and the order in which they are called.

    Defining utility functions. Student Learning Outcomes:

    You will: Be able to use object name or a reference to an object or a pointer to an

    object to access different class members.

    Be able to declare destructor for any class to perform termination

    housekeeping.

    Be able to identify the order in which the constructors and destructors are

    called for a set of objects (which have different storage classes (automatic

    or static) and different scopes (local and global)).

    Be able to write utility function and use it.

    Background: You have learned the basic concept of using handlings to access class members. You have also learned how to write a destructor for a given class.

    You have also known what the utility function is. Assumption:

    Read the summary in page#6 that explains the Order of constructor,

    destructor function calls for global, static, and local objects.

  • 10 | P a g e

    CS118 Lab Manual Fall 2012

    LIST OF Exercises:-

    Exercise #1: Write a class implementation for a class named My_Class giving the specification below:

    Data that is associated with this class are: ID: of type integer. Msg: of type string, to hold a simple description of any created object (local, global, static, or automatic).

    Member Functions:

    Constructor with 2 arguments to: - Initialize object data members ID and Msg with any given value.

    - print the following statement cout

  • 11 | P a g e

    CS118 Lab Manual Fall 2012

    Solution: #include #include using namespace std;

    class my_class { int id; string msg;

    public: my_class(int i,string s) { id=i; msg=s; cout

  • 12 | P a g e

    CS118 Lab Manual Fall 2012

    Exercise #2:

    Write a full documented and separated interface C++ program that implements a class called Employee, giving the specification below:

    Data that is associated with an Employee class:

    o Name: a private data member of type string for employee name. o Id: of type integer to hold employee number.

    o an array to hold the monthly salaries of that employee Functions that can be performed on Employee class:

    o Default constructor: to initialize object data members to default

    values.

    o Constructor with arguments to initialize object data members to any given values.

    o Utility function to calculate the annual salary of the employee. o TAX function to calculate and return the tax of any employee (which

    equals 10% of the annual salary). o Print function: that displays the name and id for that employee.

    Write a driver program that test Employee class as follow: o Create an object of type Employee called e1 using argument constructor.

    o Define a pointer to e1, and a reference to e1 of type Employee to test

    the class operations. o Try to print the values stored on e1 using the reference and then using the pointer.

    o Define another object of type Employee (named e2), and copy the values of e1 using default member wise copy.

  • 13 | P a g e

    CS118 Lab Manual Fall 2012

    Exercise #3:

    Write a full documented and separated interface C++ program that implements a class called Student, giving the specification below:

    Data that is associated with a Student class: o An array to hold the marks of the student in different courses. o Name: of type string to hold student name.

    Functions that can be performed on Student class: o Parameterized constructor to initialize object data members to any given

    values. o SetAll function: to assign new values to the data members. o Utility function to calculate the summation of student marks. o Average function: to calculate the average of the student marks. o Print function: to print the information of the student.

    Write a driver program that test class Student as follows: o Define an object of type student named s1, a pointer to s1 named ptr1, and

    a reference to s1 named ref1. o Print the values of s1. o Compute the average of s1 using the pointer ptr1. o Change the values of s1 by calling the function setAll using the reference

    ref1. o Print the information of s1.

  • 14 | P a g e

    CS118 Lab Manual Fall 2012

    Order of constructor, destructor function calls:

    1. Global scope objects

    Constructors Before any other function (including main)

    Destructors When main terminates (or exit function called) Not called if program terminates with abort

    2. Automatic local objects

    Constructors When objects defined

    Each time execution enters scope Destructors

    When objects leave scope Not called if program ends with exit or abort

    3. static local objects

    Constructors Exactly once

    When execution reaches point where object defined Destructors

    When main terminates or exit function called Not called if program ends with abort.

  • 15 | P a g e

    CS118 Lab Manual Fall 2012

    Task #4:

    - Principle of least privilege using const (constant) objects and const member functions. - Composition.

    Objectives:

    Specify const (constant) objects and const member functions.

    Create objects composed of other objects.

    Student Learning Outcomes: You will:

    Be able to specify const (constant) objects and const member functions.

    Be able to create objects composed of other objects.

    Background:

    You have learned how to write and specify const objects and member function. You have also learned how to use composition by creating object as Members of other Classes.

    Assumptions:

    All displays that your application produces are informative and clearly

    inform the user what the user is expected to do and in what order this

    should be done.

    Use the #ifndef.. #endif construct to make sure the header file is not

    included more than once. Member functions that do nothing but acquire data from an object are obvious candidates for being made const, because they dont need to modify any data.(display and get functions)

  • 16 | P a g e

    CS118 Lab Manual Fall 2012

    LIST OF Exercises:-

    Exercise #1: Suppose that you have the following class interface class Myclass { public: Myclass ( float v1 = 0, float v2 = 1 ); void addFun () ; float get_val2()const; void print() const; private: float val1; const float val2; }; Now you have to: 1. Write the appropriate definition for the constructor.

    2. Write the definition of addFun()function that add the val2 value to the current val1 value .

    3. Write the appropriate definition for the get_val2()function that return the value of the val2 data member.

    4. Write the appropriate definition for the print function that print the

    values of the class data members. Write a driver program that test Myclass class as follow:

    o Define an object (named obj1) with any values. o Define a constant object (named obj2) with any values.

    o Let the obj1 invoke these functions and specify if any will cause an error, explain why and suggest the solution:

    Call addFun(). Call get_val2(). Call print().

    o Let the obj2 invoke these functions and specify if any will cause an

    error, explain why and suggest the solution: Call addFun(). Call get_val2(). Call print().

    Try to add these two functions to the class, and specify if any will cause an

    error, explain why and suggest the solution: void set_val2(float x) {val2=x;}

    void fun(float x)const {val1=val2+x;}

  • 17 | P a g e

    CS118 Lab Manual Fall 2012

    Solution:

    #include using namespace std;

    class Myclass { public: Myclass ( float v1 = 0, float v2 = 1 ); void addFun () ; void subFun () ; float get_val2()const; void print() const;

    void set_val2(float x);

    void Myclass:: fun(float x)const;

    private: float val1; const float val2; };

    Myclass::Myclass ( float v1 , float v2 ):val1(v1),val2(v2) {}

    void Myclass::addFun () { val1+=val2; }

    float Myclass::get_val2()const { return val2; }

    void Myclass::print() const { cout

  • 18 | P a g e

    CS118 Lab Manual Fall 2012

    { //val1=val2+x;//const member function not allowed to modify data members

    } void main() { Myclass obj1(5,10); const Myclass obj2;

    obj1.addFun(); cout

  • 19 | P a g e

    CS118 Lab Manual Fall 2012

    Exercise #2: Composition

    Given the following two classes:

    class course{ int courseNumber; int creditHours; public: void setCourse (int x,int y); };

    class section{ int secNumber; course c;//composition public: void setSection (int,int,int);

    };

    a) Provide a meaningful implementation for class course and section.

    b) Write a main program that declares an array of 7 objects of type section and set their values to:

    courseNumber: 117 for all sections. creditHours: 3 for all sections.

    sectionNumber: give each section a unique number from 1-7

    Hint: Use loops.

  • 20 | P a g e

    CS118 Lab Manual Fall 2012

    Task #5: Composition. Copy Constructor.

    Friend functions.

    Objectives:

    Identify how member objects are constructed in the order in which they are declared in the class definition and before their enclosing class objects are constructed.

    Write and use copy constructor. Use friend functions.

    Student Learning Outcomes:

    You will:

    Be able to identify the order in which the constructors and destructors are

    called for member objects.

    Be able to write friend functions and use it.

    Background:

    You have learned how to create objects composed of other objects. You have also learned how to write a friend function.

  • 21 | P a g e

    CS118 Lab Manual Fall 2012

    LIST OF Exercises:-

    Exercise #1: Write and execute the following code, Notice the order of constructer and destructor:

    #include using namespace std;

    class A{ int a1; public: A():a1(0) {cout

  • 22 | P a g e

    CS118 Lab Manual Fall 2012

    Exercise #2:

    Now, add the following copy constructor to the class A,and observe the difference in output:

    A(const A& obj) { a = obj.a; cout

  • 23 | P a g e

    CS118 Lab Manual Fall 2012

    Homework:

    Giving the author class and the book class, answer the questions below:

    class Author{

    string fname; string lname; public: Author(string,string ); void print( ); void insert_author(----------); }; class book{ string book_name; int ISBN; ----------------- //composition public: book(---------------);//constructor with 3 parameters void print(); void insert_book (---------------------); };

    o Define an object of type author in class book in the line referred to by //composition

    o Write the implementation for class author and book. o Write main program that will

    o Write a driver program that test the class as follow:

    1. Define an array of 3 elements of type book. 2. Insert values for these 3 books.

    3. Print values of these 3 books in a table.

    o Write a friend function for class book that will search for a given book

    according to its ISBN. If it is found you will print the information of

    that book (book_name, ISBN, author), if not it is not found print "Not

    found".

  • 24 | P a g e

    CS118 Lab Manual Fall 2012

    Task #6: Friend function & friend class. Create and destroy objects dynamically.

    Static data members and member functions.

    Objectives:

    Using friend functions, and friend classes.

    Using this pointer. Creating and destroying objects dynamically with operators new and delete, respectively.

    Creating dynamic array class.

    Using static data members and member functions. Student Learning Outcomes:

    You will: Be able to write a friend function and friend class.

    Be able to allocate and de allocate objects dynamically.

    Background:

    You have learned the syntax of friend function, friend class, this pointer, and delete and new operators. You have also learned how to write a static

    data members and member functions.

  • 25 | P a g e

    CS118 Lab Manual Fall 2012

    LIST OF Exercises:-

    Exercise #1: Cascaded member-function calls using this pointer

    Given the following class interface of a rectangle:

    class rectangle { float left; float right;

    float top; float bottom; public:

    rectangle(float=1, float=1, float=1, float=1 );

    rectangle &setLeft(float l); rectangle &setRight(float r);

    rectangle &setTop(float t); rectangle &setBottom(float b);

    void print () const; friend void area(const rectangle & rec1);

    }

    1. Provide a meaningful implementation for the class rectangle. 2. Write a main program that test class rectangle as follow :

    o Declare an object of type rectangle called rect. o Invoke the functions setLeft, setRight, setTop, and setBottom in the same statement.

    o Calculate the area for this object. o Invoke the function print ().

  • 26 | P a g e

    CS118 Lab Manual Fall 2012

    Exercise #2: Dynamic memory management:

    Write a class called array according to the following interface: class array{ public:

    array(int = 10);

    ~array(); void read(); void print();

    int sum();

    private: int *ptr;

    int size; };

    1. Write the class implementation according to the following:

    o Constructor: that will receive the number of elements of the array. If it is positive; accept it and store it in the size. If not, let the size to be 10. Then create the array dynamically and

    store zeros as initial values of its elements. o Destructor: that will delete the array dynamically. o Read: that read and stores the values for the array. o Print: that prints the elements of the array.

    o Sum: that returns the summation of the array elements.

    2. Write a driver program to test class array and its functions as follow:

    o Declare tow objects of type Array called arr1 and arr2, with size 7 and 10 respectively.

    o Invoke read function by object arr1. o Invoke print function by object arr2.

    o Declare an object dynamically of type Array using pointer ptr

    with size 5. o Invoke print function using ptr. o Destroy the object which is pointed to by ptr.

  • 27 | P a g e

    CS118 Lab Manual Fall 2012

    Exercise # 3: Static Data Members & Member Functions:

    Given the following class Section interface: class Section { private:

    int secNum; string secName; public: Section(int, string);

    void setSection(int,string); void print()const;

    };

    Write another class named Student giving the specification below: 1. Data that is associated with this class are

    o Stname: of type string. o stnumber :of type int. o stsection :of type Section

    o NumberOfHours :static integer data member initialized to zero 2. Member Functions:

    o constructor: that initialize the data members to any given

    values. HINT:(Student(string n,int num,Section & sec)...etc. )

    o void SET_STUDENT(string n,int num,Section & sec):that set the values of any stusent object.

    o void print: that print the values of any Student object. o INCREMENT3 :static member function to increment the value of

    NumberOfHours by 3 when its called. o getNumberOfHours :static member function to return the value

    of NumberOfHours

    3. Write a driver program that test the class as follow:

    o Invoke getNumberOfHours function. o Invoke INCREMENT3 function. o Invoke getNumberOfHours function. o Declare an object of type Student enrolled at your Section object(it

    has your Section object for the value of stsection (SSS). o Invoke INCREMENT3 function. o Invoke getNumberOfHours function. o Invoke SET_STUDENT with your info. o print all information of your Student object .

  • 28 | P a g e

    CS118 Lab Manual Fall 2012

    Task #7: operator overloading.

    Objectives:

    Overload the stream insertion and stream extraction operators as global functions. Overload a number of basic operators.

    Use Operator Functions as Class Members vs. Global Functions.

    Student Learning Outcomes:

    You will:

    Be able to write and use operator overloading functions.

    Background: You have learned the fundamentals of Operator Overloading and the

    restrictions on Operator Overloading.

    Assumptions:

    Use operator overloading when it makes a program clearer than

    accomplishing the same operations with function calls.

  • 29 | P a g e

    CS118 Lab Manual Fall 2012

    LIST OF Exercises:-

    Exercise #1:

    Write a class implementation for a class named PhoneNumber giving the

    specification below: Data that is associated with this class are:

    o FName of type string. o LName of type string. o Phnum of type string.

    Functions:

    o Constructor: that initializes any object of type PhoneNumber.

    o Overloaded function for insertion operator () to read in for any object of type PhoneNumber all the values for its data members.

    Write a driver program that test the class as follow:

    o Declare an object of type PhoneNumber, read in its values then print it (using operator).

    o Declare an array of three objects of type PhoneNumber, read in their values then print their values (using operator).

  • 30 | P a g e

    CS118 Lab Manual Fall 2012

    Exercise #2:

    Suppose that you have a Point class which represents any point with (x, y) coordinates. Where X, Y are both integers in this class.

    You will overload some operators to work with object of this class.(you have to decide whether to overload the operator as a member function or as a friend function .If its O.K. try to overload that function as a member

    function and as a friend function. The operators are:

    - () operator, to input (X, Y) values from keyboard.

    - (+) operator, to add an integer value to (X, Y) values. - (+) operator, to add two points. - (+=) operator, to add an integer value to(X, Y) values. - (==) operator, to test if two points are equal or not.

    - (!) Operator, to swap (X, Y) values to be (Y, X) . - (/) operator, to find the distance between two points. - (++) operator, for post increment. - (++) operator, for pre increment.

  • 31 | P a g e

    CS118 Lab Manual Fall 2012

    Exercise #3:

    Write a class implementation for a class named Fraction giving the specification below:

    Fractions are of the form a / b, where a is the numerator and b is the denominator. So, data that is associated with this class are:

    - a: integer number that represent the numerator.

    - b: integer number that represent the denominator, and b is not 0.

    In addition you have to provide the following methods:

    1. Fraction(int n = 0, int d = 1); 2. int getNum() const;

    3. int getDenom() const; 4. Fraction operator+(const Fraction& f2); 5. Fraction operator-(const Fraction& f2);

    6. Fraction operator*(const Fraction& f2); 7. Fraction operator/(const Fraction& f2);

    Write a driver program which tests all the methods you wrote. Write necessary

    code to produce the output below. Of course you must create appropriate Fraction

    objects and call methods to produce this result.

    The output of the program should be:

    1/3 + 5/8 = 23/24 1/3 - 5/8 = -7/24

    1/3 * 5/8 = 5/24 1/3 / 5/8 = 8/15

    Notes on the methods and functions:

    Arithmetic operations on fractions are defined by the following rules: o a / b + c / d = (ad + bc) / bd o a / b - c / d = (ad - bc) / bd

    o a / b * c / d = ac / bd o (a / b) / (c / d) = ad / bc (where c/d is not 0) .

  • 32 | P a g e

    CS118 Lab Manual Fall 2012

    Task #8: Inheritance & Polymorphism.

    Objectives:

    Creating classes by inheriting from existing classes.

    Using virtual functions to achieve polymorphism behavior on inheritance hierarchy.

    Student Learning Outcomes:

    You will be able to: Promotes software reusability by inheritance.

    Declare and use virtual functions to affect polymorphism.

    Background:

    You have learned how to create classes by inheriting from existing classes.

    Declare and use virtual functions.

  • 33 | P a g e

    CS118 Lab Manual Fall 2012

    LIST OF Exercises:-

    Exercise #1: Define a class called student that has the following data members:

    - int student number - string student name - double student average

    The following member functions: - Constructor that initialize the data members with default values. - set and get functions for each data member - Print function to print the values of data members.

    Define a class called graduatestudent that inherits data members and

    functions from the class student, and then declare the following data members :

    - int level - int year

    Member functions: - constructor -set and get functions for each data member - Print function.

    Define a class called master that inherits data members and functions from

    graduatestudent class, and then declare the following data member: - int newid.

    Member function: - constructor - set and get function for the data member - Print function.

    Write a driver program that: - Declare object of type student with suitable values then print it - Declare object of type master with your information then print it.

  • 34 | P a g e

    CS118 Lab Manual Fall 2012

    Exercise #2:

    Define a base class called Worker that has two derived classes: Employee and Manager. For workers, we only have simple attributes such as their

    names and working hours. For employees and managers, each has specific attributes unique to the class. Employees have attributes such as the name of the department that they are working with, and their salaries. Managers have attributes such as the number of managed employees and the number

    of projects that theyre in charge. Also, define another class called Project that has attributes such as the name and the current progress (in %) of the project.

    (1) Write the corresponding constructors that initialize the attributes for

    classes. (2) Write the corresponding member functions to set and get the attributes for classes.

    Finally, test the classes in a main program. In the test program, you should dynamically allocate some employees and managers, print their corresponding information.

  • 35 | P a g e

    CS118 Lab Manual Fall 2012

    Exercise #3:

    Study the following code and analyze the result: # include class Vehicle { public: Vehicle(char* regnum): myRegNum(regnum) {}

    ~Vehicle(void) { delete[] myRegNum; }

    virtual void Describe(void){ cout

  • 36 | P a g e

    CS118 Lab Manual Fall 2012

  • 37 | P a g e

    CS118 Lab Manual Fall 2012

    Quizzes Description:

    Quiz#1: Aim: Writing a full documented and separated interface C++ program that implements any given class.

    Quiz#2: Aim: dealing with objects using reference and pointer. Writing a class that contain object from another class [Composition]

    Quiz#3:

    Aim: Creating and destroying objects dynamically with operators new and delete.

    Operator overloading. Writing static data members and member function.