Module 1. C++ Classes Exercises

Similar documents
Short Notes of CS201

CS201 - Introduction to Programming Glossary By

I BCS-031 BACHELOR OF COMPUTER APPLICATIONS (BCA) (Revised) Term-End Examination. June, 2015 BCS-031 : PROGRAMMING IN C ++

Interview Questions of C++

CHAPTER 1 Introduction to Computers and Programming CHAPTER 2 Introduction to C++ ( Hexadecimal 0xF4 and Octal literals 031) cout Object

AN OVERVIEW OF C++ 1

Introduction to C++ Systems Programming

Page. No. 1/15 CS201 Introduction to Programmming Solved Subjective Questions From spring 2010 Final Term Papers By vuzs Team

KOM3191 Object Oriented Programming Dr Muharrem Mercimek OPERATOR OVERLOADING. KOM3191 Object-Oriented Programming

CS3157: Advanced Programming. Outline

I BSc(IT) [ Batch] Semester II Core: Object Oriented Programming With C plus plus - 212A Multiple Choice Questions.

Come and join us at WebLyceum

Absolute C++ Walter Savitch

OBJECT ORIENTED PROGRAMMING. Ms. Ajeta Nandal C.R.Polytechnic,Rohtak

Object Oriented Programming with c++ Question Bank

CS201 Some Important Definitions

G52CPP C++ Programming Lecture 14. Dr Jason Atkin

Chapter 15 - C++ As A "Better C"

3.Constructors and Destructors. Develop cpp program to implement constructor and destructor.

CISC 2200 Data Structure Fall, C++ Review:3/3. 1 From last lecture:

C++ (Non for C Programmer) (BT307) 40 Hours

COMP 2355 Introduction to Systems Programming

Introduction to C++ Introduction to C++ 1

Problem Solving with C++

Introduction to Computers and C++ Programming p. 1 Computer Systems p. 2 Hardware p. 2 Software p. 7 High-Level Languages p. 8 Compilers p.

CS304 Object Oriented Programming Final Term

Dynamic Data Structures

Pointers, Dynamic Data, and Reference Types

Preface to the Second Edition Preface to the First Edition Brief Contents Introduction to C++ p. 1 A Review of Structures p.

C++ 8. Constructors and Destructors

COMP 2355 Introduction to Systems Programming

Object Oriented Programming. Solved MCQs - Part 2

EINDHOVEN UNIVERSITY OF TECHNOLOGY Department of Mathematics and Computer Science

Quiz Start Time: 09:34 PM Time Left 82 sec(s)

CS201 Latest Solved MCQs

CMPS 221 Sample Final

Programming. C++ Basics

Government Polytechnic, Muzaffarpur. Name of the Lab: OBJECT ORIENTED PROGRAMMING

Object oriented programming

Introduction to Programming Using Java (98-388)

STUDY NOTES UNIT 1 - INTRODUCTION TO OBJECT ORIENTED PROGRAMMING

Ch. 12: Operator Overloading

CHAPTER 4 FUNCTIONS. 4.1 Introduction

CSE 333 Lecture 9 - intro to C++

KLiC C++ Programming. (KLiC Certificate in C++ Programming)

JAYARAM COLLEGE OF ENGINEERING AND TECHNOLOGY Pagalavadi, Tiruchirappalli (An approved by AICTE and Affiliated to Anna University)

cs3157: c++ lecture #2 (mon-11-apr-2005) chronology of some programming languages... C++ vs Java identifiers.

UNIT- 3 Introduction to C++

cout << "How many numbers would you like to type? "; cin >> memsize; p = new int[memsize];

CSE 333. Lecture 9 - intro to C++ Hal Perkins Department of Computer Science & Engineering University of Washington

Jayaram college of Engineering and Technology, Pagalavadi. CS2203 Object Oriented Programming Question Bank Prepared By: S.Gopalakrishnan, Lecturer/IT

END TERM EXAMINATION

XII- COMPUTER SCIENCE VOL-II MODEL TEST I

Basic program The following is a basic program in C++; Basic C++ Source Code Compiler Object Code Linker (with libraries) Executable

Starting Savitch Chapter 10. A class is a data type whose variables are objects. Some pre-defined classes in C++ include int,

Vectors of Pointers to Objects. Vectors of Objects. Vectors of unique ptrs C++11. Arrays of Objects

An Object Oriented Programming with C

C:\Temp\Templates. Download This PDF From The Web Site

AC55/AT55 OBJECT ORIENTED PROGRAMMING WITH C++ DEC 2013

Fast Introduction to Object Oriented Programming and C++

Object Oriented Programming

Homework 4. Any questions?

CMSC 202 Section 010x Spring Justin Martineau, Tuesday 11:30am

Lecture 8. Xiaoguang Wang. February 13th, 2014 STAT 598W. (STAT 598W) Lecture 8 1 / 47

cout<< \n Enter values for a and b... ; cin>>a>>b;

Chapter 16: Exceptions, Templates, and the Standard Template Library (STL)

Babaria Institute of Technology Computer Science and Engineering Department Practical List of Object Oriented Programming with C

7.1 Optional Parameters

2 ADT Programming User-defined abstract data types

Programming in C++: Assignment Week 8

Object Oriented Software Design II

Introduction to Computer Science Midterm 3 Fall, Points

Introduction to C++ Professor Hugh C. Lauer CS-2303, System Programming Concepts

CSC 330 Object-Oriented Programming. Exception Handling CSC 330

Outline. 1 Function calls and parameter passing. 2 Pointers, arrays, and references. 5 Declarations, scope, and lifetimes 6 I/O

Come and join us at WebLyceum

W8.2 Operator Overloading


Chapter 18 - C++ Operator Overloading

public : int min, hour ; T( ) //here constructor is defined inside the class definition, as line function. { sec = min = hour = 0 ; }

6.096 Introduction to C++ January (IAP) 2009

Structured Data. CIS 15 : Spring 2007

SRM ARTS AND SCIENCE COLLEGE SRM NAGAR, KATTANKULATHUR

Collected By Anonymous

Question 1 Consider the following structure used to keep employee records:

Lecture 18 Tao Wang 1

1. Describe History of C++? 2. What is Dev. C++? 3. Why Use Dev. C++ instead of C++ DOS IDE?

21. Exceptions. Advanced Concepts: // exceptions #include <iostream> using namespace std;

G52CPP C++ Programming Lecture 13

Faculty of Information and Communication Technologies

Classes and Objects. Class scope: - private members are only accessible by the class methods.

Standard. Number of Correlations

Exam 3 Chapters 7 & 9

IS 0020 Program Design and Software Tools

CS

Object Oriented Programming CS250

Pointers. Addresses in Memory. Exam 1 on July 18, :00-11:40am

Introduction. W8.2 Operator Overloading

Tokens, Expressions and Control Structures

SRI SARASWATHI MATRIC HR SEC SCHOOL PANAPAKKAM +2 IMPORTANT 2 MARK AND 5 MARK QUESTIONS COMPUTER SCIENCE VOLUME I 2 MARKS

Transcription:

Module 1. C++ Classes Exercises 1. The ZooAnimal class definition below is missing a prototype for the Create function. It should have parameters so that a character string and three integer values (in that order) can be provided when it is called for a ZooAnimal object. Like the Destroy function, it should have return type void. Write an appropriate prototype for the ZooAnimal Create function. void Destroy (); // destroy function 2. Write a function header for the ZooAnimal class member function dayssincelastweighed. This function has a single integer parameter today and returns an integer number of days since the animal was last weighed. void ZooAnimal::Destroy () delete [] name; // -------- member function to return the animal's name char* ZooAnimal::reptName () return name; // -------- member function to return the number of days // -------- since the animal was last weighed int startday, thisday; thisday = today/100*30 + today - today/100*100; startday = weightdate/100*30 + weightdate - weightdate/100*100; if (thisday < startday) thisday += 360; return (thisday-startday); 3. In the main function there is a cout statement that attempts to print the animal's name. However, it is not allowable because it attempts to access the private data member called name. Modify that statement so that it uses a public member function that returns the ZooAnimal's name.

void Create (char*, int, int, int); // create function void Destroy (); // destroy function // -------- member function to return the animal's name char* ZooAnimal::reptName () return name; // ========== an application to use the ZooAnimal class void main () ZooAnimal bozo; bozo.create ("Bozo", 408, 1027, 400); cout << "This animal's name is " << bozo.name << endl; bozo.destroy (); 1. Write the ZooAnimal inline member function reptweightdate. It should simply return the weightdate data member. enum scale ounces, kilograms void Create (char*, int, int, int); // create function void Destroy (); // destroy function void changeweightdate (int today); void reptweight (scale which); inline int reptweightdate (); 2. Modify the prototype for changeweightdate below to make it the appropriate single line inline member function changeweightdate. The single line needed should set the data member weightdate equal to the parameter today. enum scale ounces, kilograms

void Create (char*, int, int, int); // create function void Destroy (); // destroy function inline void changeweightdate (int today); void reptweight (scale which); int reptweightdate (); 3. Write the ZooAnimal member function ismotherof. It needs only a single statement that makes the mother data member of the ZooAnimal object parameter a pointer to the ZooAnimal object for which this function is called. ZooAnimal *mother; void Create (char*, int, int, int); // create function void Destroy (); // destroy function void ismotherof (ZooAnimal&); void changeweightdate (int today); void reptweight (scale which); inline int reptweightdate () return weightdate;

Module 2. Class Member Functions Exercises 1. Write the ZooAnimal inline member function reptweightdate. It should simply return the weightdate data member. enum scale ounces, kilograms void Create (char*, int, int, int); // create function void Destroy (); // destroy function void changeweightdate (int today); void reptweight (scale which); inline int reptweightdate (); 2. Modify the prototype for changeweightdate below to make it the appropriate single line inline member function changeweightdate. The single line needed should set the data member weightdate equal to the parameter today. enum scale ounces, kilograms void Create (char*, int, int, int); // create function void Destroy (); // destroy function inline void changeweightdate (int today); void reptweight (scale which); int reptweightdate (); 3. Write the ZooAnimal member function ismotherof. It needs only a single statement that makes the mother data member of the ZooAnimal object parameter a pointer to the ZooAnimal object for which this

function is called. ZooAnimal *mother; void Create (char*, int, int, int); // create function void Destroy (); // destroy function void ismotherof (ZooAnimal&); void changeweightdate (int today); void reptweight (scale which); inline int reptweightdate () return weightdate;

Module 3. Constructors and Destructors Exercises 1. Create the ZooAnimal constructor function. The function has 4 parameters -- a character string followed by three integer parameters. In the constructor function dynamically allocate the name field (20 characters), copy the character string parameter into the name field, and then assign the three integer parameters to cagenumber, weightdate, and weight respectively. ~ZooAnimal (); // destructor function 2. Modify the function header below for the constructor function for ZooAnimal. Provide default values of "Nameless" for who, 9999 for whichcage, 101 (January 1) for weighday, and 100 for pounds. // ---------- the constructor function ZooAnimal::ZooAnimal (char* who, int whichcage, int weighday, int pounds) char *name = new char[20]; strcpy (name, who); cagenumber = whichcage; weightdate = weighday; weight = pounds; 3. Write a ZooAnimal member conversion function that converts a type ZooAnimal to produce a value of type int. The function should simply return the cagenumber data member. operator int (); // member conversion function inline ~ZooAnimal () // destructor function

Module 4. Static Members, Friends Exercises 1. Add the following below: Declare the integer static data member oldestweightdate. Create the static member function changeoldestweightdate with void return type and a single integer parameter. Set oldestweightdate to that parameter. Do not forget a function prototype for changeoldestweightdate. Also, be sure to define the static member at global scope. 2. Write a non-member function reptoldestzooanimalweightdate that returns the value of the ZooAnimal class static data member oldestweightdate. static int oldestweightdate; static changeoldestweightdate (int date); static int reptoldestweightdate (); int ZooAnimal::oldestWeightDate; //define static member at global scope 3. Write the ZooAnimal member function reptnutrition that returns the result of the member function reptmealnutrition from the nested class nutrition invoked on the ZooAnimal class data member nutr.

class nutrition int numbermeals; int maxpoundsfed; float avgnutrvalue; inline nutrition () numbermeals = 4; maxpoundsfed = 75; avgnutrvalue = 38.21; // constructor function inline float reptmealnutrition () return numbermeals * avgnutrvalue; nutrition nutr; float reptnutrition (); 4. Declare that the class cageassignment is a friend class to ZooAnimal. ~ZooAnimal (); // destructor function 5. Write the changecage member function of class cageassignment. It should set the data member cagenumber of the ZooAnimal object parameter to the value of the cageassignment data member enclosure and then increment enclosure. ; class cageassignment int enclosure; inline cageassignment (int num) enclosure = num; // constructor inline ~cageassignment () // destructor function void changecage (ZooAnimal&); int reptcage (ZooAnimal&);

6. Write a function prototype for the friend function declaration which is the cageassignment class member function reptcage. This function has a single ZooAnimal parameter (called by reference) and returns an integer value. ; class cageassignment int reptcage (ZooAnimal&); ~ZooAnimal (); // destructor function

Module 5. Linked Lists, Stacks, Queues Exercises 1. Complete the ZooAnimal constructor function. It should insert the new ZooAnimal class object in the linked list at the end after the object currently pointed to by the static data member current. Make the nextanml pointer of the current object point to the object being constructed. Be sure to update the pointer current. ZooAnimal* prevanml; ZooAnimal* nextanml; static ZooAnimal *start; static ZooAnimal *current; ZooAnimal (char*); ~ZooAnimal (); char* reptname () return name; ZooAnimal* prevanimal (); // previous link in the list // next link in the list // first element of linked list // last element of linked list // constructor function // destructor function ZooAnimal* ZooAnimal::start = NULL; ZooAnimal* ZooAnimal::current = NULL; ZooAnimal::ZooAnimal (char* thename) char *name = new char[20]; strcpy(name, thename); 2. The destructor function is called to destroy the last item in the linked list. The pointer to the object being destroyed is the this pointer. The destructor function updates the static data member current. Write the destructor function. Make current the same as the prevanml pointer of the object being destroyed. ZooAnimal* prevanml; ZooAnimal* nextanml; static ZooAnimal *start; static ZooAnimal *current; ZooAnimal (char*); ~ZooAnimal (); char* reptname () return name; ZooAnimal* prevanimal (); // previous link in the list // next link in the list // first element of linked list // last element of linked list // constructor function // destructor function ZooAnimal* ZooAnimal::start = NULL;

ZooAnimal* ZooAnimal::current = NULL; 3. Modify the cout statement below so that it invokes the ZooAnimal member function reptname to report the name of the creature object denoted by subscript whichone. ~ZooAnimal (); // destructor function // ========== an application to use the ZooAnimal class void main () ZooAnimal creature [200]; int whichone = 173; cout << "This animal's name is " << << endl;

Module 6. Inheritance Exercises 1. Make the necessary changes below to indicate that the class LargeAnimal is derived from the base. Specify that the base class is public. char* name; inline ~ZooAnimal () delete [] name; // destructor function class LargeAnimal char* species; float cageminimumvolume; LargeAnimal (char*, int, int, int, float); // constructor function inline ~LargeAnimal () delete [] species; // destructor function float reptcageminimumvolume (); 2. On the cout statement for gonzo (last statement below), since the gonzo object is of type class LargeAnimal, gonzo's species will be returned by the LargeAnimal class' reptname member function. Make the necessary changes so that gonzo's name will be returned instead by the ZooAnimal class' reptname member function. char* name; inline ~ZooAnimal () delete [] name; // destructor function // -------- member function to return the animal's name char* ZooAnimal::reptName () return name;

class LargeAnimal : public ZooAnimal char* species; float cageminimumvolume; LargeAnimal (char*, int, int, int, char*, float); // constructor function inline ~LargeAnimal () delete [] species; // destructor function float reptcageminimumvolume (); // -------- member function to return the large animal's species char* LargeAnimal::reptName () return species; // ========== an application to use the LargeAnimal class void main () ZooAnimal bozo; LargeAnimal gonzo; cout << bozo.reptname () << endl; cout << gonzo.reptname () << endl; 3. Make the necessary changes below so that all calls to the ZooAnimal member function reptname are passed to the matching function in the derived type when called for an object of the derived type. char* name; inline ~ZooAnimal () delete [] name; // destructor function // -------- member function to return the animal's name char* ZooAnimal::reptName () return name; class LargeAnimal : public ZooAnimal

char* species; float cageminimumvolume; LargeAnimal (char*, int, int, int, char*, float); // constructor function inline ~LargeAnimal () delete [] species; // destructor function float reptcageminimumvolume (); // -------- member function to return the large animal's species char* LargeAnimal::reptName () return species; 4. Make the necessary changes to indicate that the class LargeAnimal is a derived class of the base classes ZooAnimal and Mammal (in that order). Specify that the base classes are public. protected: char* name; inline ~ZooAnimal () delete [] name; // destructor function class Mammal protected: float minimumvolume; int minimumweight; Mammal (float, int); // constructor function inline ~Mammal () // destructor function float reptminimumvolume (); int reptminimumweight (); class LargeAnimal protected: char* species; float cageminimumvolume; LargeAnimal (char*, int, int, int, float, float, int); // constructor inline ~LargeAnimal () delete [] species; // destructor function float reptcageminimumvolume ();

5. In the reptcageminimumvolume function below, the reference to the data name weight is ambiguous. Make the necessary changes to indicate that the weight to be used is the one from the Mammal base class. protected: char* name; inline ~ZooAnimal () delete [] name; // destructor function class Mammal protected: float minimumvolume; Mammal (float, int); // constructor function inline ~Mammal () // destructor function float reptminimumvolume (); class LargeAnimal : public ZooAnimal, public Mammal protected: char* species; float cageminimumvolume; LargeAnimal (char*, int, int, int, float, float, int); // constructor inline ~LargeAnimal () delete [] species; // destructor function float reptcageminimumvolume (); // -------- member function to return the minimum cage volume // -------- needed for this large animal float LargeAnimal::reptCageMinimumVolume () if (weight < 500) return cageminimumvolume; else return reptminimumvolume (); 6. In the reptcageminimumvolume function below, the reference to the function name reptweight is ambiguous. Make the necessary changes to indicate that the reptweight function to be used is the one from the ZooAnimal base class.

protected: char* name; inline ~ZooAnimal () delete [] name; // destructor function class Mammal protected: float minimumvolume; Mammal (float, int); // constructor function inline ~Mammal () // destructor function float reptminimumvolume (); class LargeAnimal : public ZooAnimal, public Mammal protected: char* species; float cageminimumvolume; LargeAnimal (char*, int, int, int, float, float, int); // constructor inline ~LargeAnimal () delete [] species; // destructor function float reptcageminimumvolume (); // -------- member function to return the minimum cage volume // -------- needed for this large animal float LargeAnimal::reptCageMinimumVolume () if (Mammal::weight < 500) return cageminimumvolume; else return reptweight ();

Module 7. Overloading Operators Exercises 1. Write the member function to overload the == operator. Use the standard == operator to compare the weightdate data member of the ZooAnimal object to the integer parameter. int operator== (int); 2. Write the member function to overload the auto-decrement operator. Use the standard -= operator to decrease the ZooAnimal object's weight by 1 (pound). void operator-- (); 3. Write the member function to overload the function call operator. Give the parameter the value of the data member cagenumber. void operator() (int&); // ========== an application to use the ZooAnimal class void main () ZooAnimal bozo ("Bozo", 408, 1027, 400); int cage;

bozo(cage); cout << cage << endl;

Module 8. Class Templates Exercises 1. The is going to become a Class Template. Declare a class template with a single template type parameter weighttype. Declare the data name weight to be of whatever type is used for weighttype. Make the last parameter to the constructor function to be of weighttype. The constructor function is not in the body of class template ZooAnimal. Modify it so that it shows that this is the constructor function for the class template ZooAnimal with template type parameter weighttype. inline ~ZooAnimal () delete [] name; // destructor function // ---------- the constructor function ZooAnimal::ZooAnimal (char* who, int whichcage, int weighday, int pounds) char *name = new char[20]; strcpy (name, who); cagenumber = whichcage; weightdate = weighday; weight = pounds; 2. The class template ZooAnimal has been modified to include another template type parameter. Write a statement that declares a class template with two template type parameters: first weighttype and second cagetype. template <class weighttype, class cagetype> cagetype cagenumber; weighttype weight; ZooAnimal (char*, cagetype, int, weighttype); // constructor function inline ~ZooAnimal () delete [] name; // destructor function void changeweight (weighttype pounds); weighttype reptweight ();

3. The class template ZooAnimal once again has only the single template type parameter weighttype. Modify the declaration of object bozo so that it is the declaration of a ZooAnimal object with template type parameter weighttype to be of type integer. template <class weighttype> weighttype weight; ZooAnimal (char*, int, int, weighttype); // constructor function inline ~ZooAnimal () delete [] name; // destructor function void changeweight (weighttype pounds); weighttype reptweight (); // ---------- the constructor function template <class weighttype> ZooAnimal<weightType>::ZooAnimal (char* who, int whichcage, int weighday, weighttype pounds) char *name = new char[20]; strcpy (name, who); cagenumber = whichcage; weightdate = weighday; weight = pounds; // ========== an application to use the ZooAnimal class void main () ZooAnimal bozo ("Bozo", 408, 1027, 400);

Module 9. I/O Stream Libraries Exercises 1. The cout statement below outputs a spectrum value and a team character string. Modify this line using the setw function so that each spectrum value is output in a field 10 characters wide and each team string is output in a field 8 characters wide. #include <iostream.h> void main() float spectrum[] = 6.24, 3.87, 5.06, 2.19, 4.38 char *team[] = "Bozo", "Gonzo", "Rollo", "Marco" for (int level = 0; level < 4; level++) cout << spectrum[level] << team[level] << endl; 2. Modify the cout statement below to specify that 2 digits of precision are to be used when printing spectrum's floating point values. #include <iostream.h> void main() float spectrum[] = 6.24, 3.87, 5.06, 2.19, 4.38 for (int level = 0; level < 5; level++) cout << spectrum[level] << endl; 3. Write the function that defines the overloaded >> operator for ZooAnimal objects to input values for the name, cage number, weight date, and weight (respectively) of the ZooAnimal object parameter. inline ~ZooAnimal () delete [] name; // destructor function friend ostream& operator<< (ostream& stream, ZooAnimal& Z); friend istream& operator>> (istream& stream, ZooAnimal& Z);

Module 10. Exception Handling Exercises 1. On the blank line below write a statement that throws an InvalidInput object (with an empty parameter list) if the variable number is greater than 99. class InvalidInput void factorial (int& facto, int number) if (number > 99) else facto = 1; int n = 1; while (++n <= number) facto *= n; 2. Modify the last line below so that the block of code represented by /**/ is a Catch Handler for exceptions of type InvalidInput. class InvalidInput void factorial (int& facto, int number) if (number > 99) throw InvalidInput (); else facto = 1; int n = 1; while (++n <= number) facto *= n; void main() int east, eastfact; int west, westfact; cin >> east; cin >> west; try factorial (eastfact, east); factorial (westfact, west); // end of try block /**/

3. Modify the changeweight prototype so that it specifies that function changeweight may only throw an exception of type UnderWeight. class UnderWeight //exception class static int minweight; void changeminweight (int); void changeweight (int);