Docsity
Docsity

Prepare for your exams
Prepare for your exams

Study with the several resources on Docsity


Earn points to download
Earn points to download

Earn points by helping other students or get them with a premium plan


Guidelines and tips
Guidelines and tips

Object oriented programming (C++), Exercises of Object Oriented Programming

Object oriented programming revision questions

Typology: Exercises

2017/2018
On special offer
30 Points
Discount

Limited-time offer


Uploaded on 06/09/2018

omaramro
omaramro 🇯🇴

4.7

(3)

1 document

Partial preview of the text

Download Object oriented programming (C++) and more Exercises Object Oriented Programming in PDF only on Docsity! Page 1 of 28 Answers: Question 1: What is the output in each of the following code? A B #include<iostream.h> class item { int code; public: item() { } item(int n) { code=n; } item(item & a) { code=a.code+1; } void show(void) { cout<<code; } }; int main() { item obj1(12); item obj2(obj1); item obj3=obj1; item obj4; obj4=obj1; cout<<"\n code of obj1 : "; obj1.show(); cout<<"\n code of obj2 : "; obj2.show(); cout<<"\n code of obj3 : "; obj3.show(); cout<<"\n code of obj4 : "; obj4.show(); return 0; } #include <iostream> using namespace std; class myClass{ public: int val; myClass () { val = -1; } void f1 (myClass obj) { obj.val = 3; } void f2 (myClass& obj) { obj.val = 5; } }; int main() { myClass obj1, obj2; obj1.f1(obj2); cout << "obj2.val is " << obj2.val << endl; obj1.f2(obj2); cout << "obj2.val is " << obj2.val << endl; return 0; } Output code of obj1 : 12 code of obj2 : 13 code of obj3 : 13 code of obj4 : 12 Output obj2.val is -1 obj2.val is 5 Page 2 of 28 Question 2: Given the following code, indicate whether or not each of the following lines (a) through (h) is legal or illegal. If it is illegal you have to give a reason. #include <iostream> using namespace std; class myClass { private: double x = 70.0; //a public: int i; int myClass() //b { i = -1; x = 80.0; //c return i; //d } void f1 (int j) const { i = j; //e } }; main() { myClass obj; //f obj.f1(4); cout << "obj.i is " << obj.i << endl; //g cout << "obj.x is " << obj.x << endl; //h } line legal illegal reason a X Cannot initialize at declaration b X Constructor has no return type c X d X Constructor cannot return a value e X Constant function, cannot assign a value to i f X g X h X Private member Page 5 of 28 Question 4 Write a program to test the class Electricity you have written in the previous question. Your program will: a) Declare an array of Electricity objects of size 12 b) Set the amount of units and compute the cost for each element of the array. Let user enter the consumed units for each object. c) Declare an Electricity object named TOTAL_BILL. Then, with a for loop, add the 12 objects to TOTAL_BILL int main () { Electricity data[12]; double u; for (int i=0; i<12; i++) { cin >> u; data[i].setUnits(u); data[i].Bill(); } Electricity TOTAL_BILL; for (int i=0; i<12; i++) TOTAL_BILL = TOTAL_BILL.addBills(data[i]); return 0; } Page 6 of 28 Question 5 For each row in below table, specify how would you create the new class using existing class: inheritance (is-A) or composition (has-A): Existing Class New Class inheritance composition Employee Full time Employee X President Country X Hand Body X Student Computer Student X Manager Business X Shape Circle X Page 7 of 28 Question 6: 1. When class B is inherited from class A, what is the order in which the constructors of those classes are executed A. Class A first Class B next B. Class B first Class A next C. Class B's only as it is the child class D. Class A's only as it is the parent class 2. Which of the following operators below allow defining the member functions of a class outside the class? A. :: B. :? C. ? D. % 3. Which of the following can be overloaded? A. member functions B. constructors C. destructors D. A and B 4. The default access level assigned to members of a class is ___________ A. Private B. Public C. Protected D. Needs to be assigned 5. For which type of class private and protected members of the class can be accessed from outside the same class in which they are declared A. No such class exist B. Friend C. Static D. Virtual 6. The return value of the following code is Class1& test(Class1 obj) { Class1 *ptr = new Class1(); ......... return *ptr; } A. object of Class1 B. reference to ptr C. reference of Class1 D. object pointed by ptr 7. class Example{ public: int a,b,c; Example(){a=b=c=1;} //Constructor 1 Example(int a){a = a; b = c = 1;} //Constructor 2 Example(int a,int b){a = a; b = b; c = 1;} //Constructor 3 Example(int a,int b,int c){ a = a; b = b; c = c;} //Constructor 4 } In the above example of constructor overloading, the following statement will call which constructor Page 10 of 28 Question 8: A Course class is used to represent course information which contains a set of grades for certain course. Given the following Course class: class Course { public: Course(int count); ~Course(); Course( const Course &); private: int grades_count; int * grades; }; Write the implementation of the following functions: A. Course(int count): A constructor that creates an array of grades based on count and initlializes the grades count member variable. Course::Course(int count) { grades_count=count; grades= new int[grades_count]; } B. ~Course(): A destrcutor that clears the course object. Course::~Course() { delete [] grades; } C. Course( const Course &): A copy construcor. Course::Course(const Course & c) { grades_count=c.grades_count; grades= new int[grades_count]; for (int i=0;i <grades_count;i++) grades[i]=c.grades[i]; } Page 11 of 28 Question 10 Trace the following program and write the generated output in the box below only? #include<iostream.h> class Product { protected: int price; public: void set_price (int a){ price = a; } virtual int Selling_Price(){return 0;} virtual void print() { cout <<"Polygon: "<< price; } }; class Computer: public Product { public: int Selling_Price () { return price * 5 ; } void print() { cout<< "Computer: "<< price; } }; class Car: public Product { public: int Selling_Price () { return price * 10;} void print() { cout<< "Car: "<< price; } }; void main() { int i; int x[10] = {10,20,30,40,50,10,30,50,70,0}; Product *ptr[10]; ptr[0] = new Product; for(i=1; i<5 ;i++) ptr[i]= new Car; for(i=5; i<10 ;i++) ptr[i]= new Computer; for(i=0; i<10 ;i++) ptr[i]-> set_price( x[i] ); i=0; while( i < 10 ) { ptr[i]->print(); cout << " Total= "<< ptr[i]->Selling_Price(); cout << endl; i += 3; } } Polygon: 10 Total= 0 Car: 40 Total= 400 Computer: 30 Total= 150 Computer: 0 Total= 0 Page 12 of 28 Question 13 1. What does the following declaration declare? int *countPtr, count; a. Two integer variables. b. One pointer to an integer and one integer variable. c. Two pointers to integers. d. The declaration is invalid. 2. Inside a function definition for a member function of an object with data element x, which of the following is equivalent to this->x: a. *this.x b. *this->x c. x d. Both A and C are correct e. None of the above 3. One of the following is not correct when talking about static member functions: a. static member functions can only access other static member functions and static data members. b. static member functions can be called even if no object of their class is created. c. static member functions cannot be called from an object of their class. d. None of the above. 4. The correct function name for overloading the multiplication operator is: a. operator* b. operator(*) c. operator:* d. operator_* 5. A friend function defined in a class is considered a member function of that class: a. True b. False 6. With Inheritance, the order of execution for the constructors when creating an object of a derived class is as follows: a. Parent class constructor and then derived class constructor b. Derived class constructor and then parent class constructor c. There is no order of execution, parent class constructors are never called d. None of the above Page 15 of 28 class Car { public: void StartEngine() { if (tank.IsEmpty()) { cout <<" can't start car, no Gas"<<endl; return; } else engine.Start(); } void StopEngine() {engine.Stop(); } void SetGear(int level) { gear_level=level; } void StepOnGas() { switch(gear_level) { case 1: engine.MoveForward(); break; case 2: engine.MoveBackward(); break; case 3: cout <<" Vrooom Vrooom Vroooooooooooom"; break; } } void FillGas(float value){ tank.AddGas(value); } private: Engine engine; GasTank tank; int gear_level; }; Page 16 of 28 Question 17: Write a class named Cabinet. The class should have private data members named ArabicBooks, EnglishBooks and ComputerBooks all of type integer. The class should have the following: 1. A member function named GetTotalBooks to retrieve the number of all books in the cabinet. int GetTotalBooks() { return EnglishBooks+ArabicBooks+ComputerBooks; } 2. Overload the + operator to allow adding two objects of type Cabinet and return an object of same type (note, add the ArabicBooks to ArabicBooks, EnglishBooks to EnglishBooks, and so on). Cabinet operator+ (Cabinet b) { Cabinet temp; temp.EnglishBooks= EnglishBooks+b.EnglishBooks; temp.ArabicBooks= ArabicBooks+b.ArabicBooks; temp.ComputerBooks= ComputerBooks+b.ComputerBooks; return temp; } 3. Overload the – operator to allow subtracting books from the cabinet. For Example, Cabinet – 2 will return a new cabinet object with 2 books less from each type of books. If one of the categories does not have 2 books or more, it should not subtract from that category. Cabinet operator- (int value) { Cabinet temp; temp=(*this); if (EnglishBooks>=value) temp.EnglishBooks= EnglishBooks-value; if (ArabicBooks>=value) temp.ArabicBooks= ArabicBooks-value; if (ComputerBooks>=value) temp.ComputerBooks= ComputerBooks-value; return temp; } 4. Overload the > operator to compare between two cabinet objects based on their total number of books. bool operator> (Cabinet b) {return GetTotalBooks()>b.GetTotalBooks(); } Page 17 of 28 5. Overload the << operator to allow printing cabinet objects using cout. ostream & operator << ( ostream & output , const Cabinet c) { output << "Arabic " <<c.ArabicBooks<<endl; output << "Computer "<< c.ComputerBooks<<endl; output << "English " << c.EnglishBooks<<endl; return output; } In case you need to combine all: class Cabinet { public: Cabinet(int e,int a,int c) { EnglishBooks=e; ArabicBooks=a; ComputerBooks=c; } Cabinet() { EnglishBooks=0; ArabicBooks=0; ComputerBooks=0; } int GetTotalBooks() { return EnglishBooks+ArabicBooks+ComputerBooks; } Cabinet operator+ (Cabinet b) { Cabinet temp; temp.EnglishBooks= EnglishBooks+b.EnglishBooks; temp.ArabicBooks= ArabicBooks+b.ArabicBooks; temp.ComputerBooks= ComputerBooks+b.ComputerBooks; return temp; } Cabinet operator- (int value) { Cabinet temp; temp=(*this); if (EnglishBooks>=value) temp.EnglishBooks= EnglishBooks-value; if (ArabicBooks>=value) temp.ArabicBooks= ArabicBooks-value; if (ComputerBooks>=value) temp.ComputerBooks= ComputerBooks-value; return temp; } Page 20 of 28 Question 27: Trace the following programs and write the generated output in the boxes below only? A (3 points) B (4 points) #include <iostream> using namespace std; class myClass { int code; int count; public: myClass(int m=3) { count=m*2; code=m; } int f2( int v) { return v+count; } void f1(int&x,int y){ x=count; y=f2(code); } }; int main() { myClass obj1,obj2(7); int val1=3,val2=5; obj2.f1(val1,obj1.f2(val2)); cout<<"\nval1 :"<<val1; cout<<"\nval2 :"<<val2; } #include <iostream> using namespace std; class myMessage{ public: myMessage(int b=7); void print(); void f2( int); private: int c; }; myMessage::myMessage(int b) { c=b; } void myMessage::f2(int c2) { c=c2; } void myMessage::print() { cout<<c<<endl; } int main() { myMessage P,Q(5); myMessage R[5]; for (int i=0; i<3;i++) R[i].f2(i); P.print(); Q.print(); for (int i=0; i<4;i++) R[i].print(); } val1 :14 val2 :5 7 5 0 1 2 7 Page 21 of 28 Question 28: a) Write a C++ class to define a Circle, the class should have: • Three private member variables: x, y and r where (x,y) represents the center of the circle and r represents the radius of the circle. • Two constructors ( one default no arguments and one with three integer values x_val, y_val, and r_val) • SetXY( int v1,int v2) to set the values for the center. • SetRadius(int v) to set the value of the radius • Move(int dx, int dy) member function that moves the circle center by dx value for the x-axis of the center and dy for the y-axis. For example, if we have circle with center (30,32) and we apply Move(3,-8), the new center will be (33,24). • float GetArea() function that computes the area of the circle. Area is computed using the following formula: Area= π .R2 where π = 22/7 and R is the radius. • Bool IsSmaller( Circle c) to compare area of an object with object c and return true if area of object c is bigger. #include <iostream> using namespace std; class Circle { public: Circle() { x=y=r=0;} Circle(int x_val,int y_val, int r_val) { x=x_val; y=y_val; r=r_val; } void SetXY(int v1, int v2) {x=v1; y=v2; } void SetRadius(int v) {r=v; } void Move(int dx, int dy) { x+=dx; y+=dy;} float GetArea() { return (r*r*(22.0/7) );} bool IsSmaller(Circle c) { return GetArea()<c.GetArea(); } private: int x,y,r; }; Page 22 of 28 Question 29: Based on Circle class you defined in previous question, a) Write a function named ReadCircles that receives an array of objects of type circle and the size of the array, read values for the different member variables, and set them using their corresponding setters. b) Write a main function that declares an array named data of type Circle and size 10. Use ReadCircles functions to read values inside array data. c) Inside main function, move all circle objects inside the array data by move values (dx=24,dy=13) and print their area sizes. void ReadCircles( Circle a[], int size) { int x,y,r; for (int i=0;i<size;i++) { cout << " please enter values for x y and radius of a circle"<<endl; cin >> x >> y >> r; a[i].SetXY(x,y); a[i].SetRadius(r); } } int main() { Circle data[10]; ReadCircles(data,10); for (int i=0; i<10;i++) { data[i].Move(24,13); cout <<"circle number "<<i+1<<" has area "<<data[i].GetArea() <<endl; } return 0; } Page 25 of 28 Question 32 Each student at PSUT has an id, a name, a gpa, and a major. A student can be a bachelor student or a master student. Bachelor students are required to do a graduation project and training at some company. Master students are required to do a thesis. Bachelor student rating is different from Master student rating. Given the following student class: class Student {public: Student() ; Student(int i, float g, string n, string m) ; string GetMajor() ; void SetID(int id) ; void SetGPA(float gpa) ; void SetName(string name) ; void SetMajor(string major); virtual string GetRating() = 0; virtual bool IsBachelor() = 0; virtual void Print() { cout << " Student ID " << id << " Name " << name; } protected: float GetGPA() { return gpa; } private: int id; float gpa; string name; string major; }; Assume that all member functions defined in Student class are implemented. Define a new class called BachelorStudent. This class should 1. Inherit (derive) from Student class and include two new string member variables ( project_title, training_company). 2. Define a constructor to initialize all member variables (id, gpa, name,major, project_title, training_company) 3. Override GetRating function such that it returns Excellent for GPA >=84, Very good for [76 to <84), Good for [68 to <76 ) and Fair otherwise 4. Override isBachelor to return true 5. Override Print to print student id, student name, gpa, and rating. Page 26 of 28 class BachelorStudent : public Student { public: BachelorStudent(int id, float gpa, string name, string major, string project, string company) :Student(id,gpa,name,major) { project_title = project; training_company = company; } string GetRating() { float g = GetGPA(); if (g >= 84) return "Excellent"; else if (g >= 76) return "Very Good"; else if (g >= 68) return "Good"; else return "Fair"; } bool IsBachelor() { return true; } void Print() { Student::Print(); cout << " major " << GetMajor() << " Rating " << GetRating(); } void SetProject(string p) { project_title = p; } void SetCompany(string c) { training_company = c; } private: string project_title; string training_company; }; Page 27 of 28 Question 33 Based on previous question, assume that the following MasterStudent class is already implemented, class MasterStudent : public Student {public: MasterStudent(int id, float gpa, string name, string major, string thesis); string GetRating(); bool IsBachelor(); void Print(); void SetThesis(string t) ; private: string thesis;}; Also, assume that the BachelorStudent and Student classes are all implemented correctly with setters and getters for all member variables. Use these classes to accomplish the following: 1) Write a non-member function Student * ReadStudent() which takes no parameters and returns a pointer to a student object. The function asks the user to enter Bachelor or Master student and then reads the information of the selected student type and allocate and return an object accordingly. 2) Write a non-member function int CountBachelor(Student * group[], int n, string major, string rating) that receives an array of Student pointers, the size of the array n, a major and rating and returns the number of Bachelor students who have that major and that rating in the received groups array. 3) Write a main function that: A. Defines an array of Student points of size 100 B. Read 100 student objects using ReadStudent function of question 1 C. Print students information using Print function D. Count the number of students who are bachelor, of major CS and rating Excellent. /////////////////////////////////////////////////////////////////////////////////////// Student * ReadStudent() { Student * s; int type; int id; float gpa; string name, major, thesis, project, company; cout << " please enter 1 for bachelor and 2 for master"; cin >> type; if (type == 1) {