CS 211 Winter 2004 Sample Final Exam (Solutions)

Similar documents
CS 251 INTERMEDIATE SOFTWARE DESIGN SPRING C ++ Basics Review part 2 Auto pointer, templates, STL algorithms

1/29/2011 AUTO POINTER (AUTO_PTR) INTERMEDIATE SOFTWARE DESIGN SPRING delete ptr might not happen memory leak!

CE221 Programming in C++ Part 1 Introduction

Lab 2: ADT Design & Implementation

CS 162, Lecture 25: Exam II Review. 30 May 2018

ECE 462 Exam 1. 6:30-7:30PM, September 22, 2010

Operator overloading

CS 216 Fall 2007 Midterm 1 Page 1 of 10 Name: ID:

Short Notes of CS201

Type Aliases. Examples: using newtype = existingtype; // C++11 typedef existingtype newtype; // equivalent, still works

CS201 - Introduction to Programming Glossary By

pointers & references

CS 376b Computer Vision

CSE 333 Lecture 9 - intro to C++

Object-Oriented Design (OOD) and C++

Come and join us at WebLyceum

W3101: Programming Languages C++ Ramana Isukapalli

III. Classes (Chap. 3)

377 Student Guide to C++

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

COSC 320 Exam 2 Key Spring Part 1: Hash Functions

Introduction to Programming Using Java (98-388)

Outline. User-dened types Categories. Constructors. Constructors. 4. Classes. Concrete classes. Default constructor. Default constructor

SRM ARTS AND SCIENCE COLLEGE SRM NAGAR, KATTANKULATHUR

Announcements. CSCI 334: Principles of Programming Languages. Lecture 18: C/C++ Announcements. Announcements. Instructor: Dan Barowy

Wentworth Institute of Technology COMP201 Computer Science II Spring 2015 Derbinsky. C++ Kitchen Sink. Lecture 14.

Due Date: See Blackboard

FINAL TERM EXAMINATION SPRING 2010 CS304- OBJECT ORIENTED PROGRAMMING

Review: Exam 1. Your First C++ Program. Declaration Statements. Tells the compiler. Examples of declaration statements

M.C.A DEGREE EXAMINATION,NOVEMBER/DECEMBER 2010 Second Semester MC 9222-OBJECT ORIENTED PROGRAMMING (Regulation 2009)

Come and join us at WebLyceum

15: Polymorphism & Virtual Functions

CSE 333 Final Exam June 6, 2017 Sample Solution

Due Date: See Blackboard

COEN244: Class & function templates

Advanced Systems Programming

Review Questions for Final Exam

CE221 Programming in C++ Part 2 References and Pointers, Arrays and Strings

Absolute C++ Walter Savitch

CSCI 102L - Data Structures Midterm Exam #2 Spring 2011

Welcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 8/19/ Review. Here s a simple C++ program:

Homework 5. Yuji Shimojo CMSC 330. Instructor: Prof. Reginald Y. Haseltine

Do not write in this area TOTAL. Maximum possible points: 75

PIC 10A Pointers, Arrays, and Dynamic Memory Allocation. Ernest Ryu UCLA Mathematics

A506 / C201 Computer Programming II Placement Exam Sample Questions. For each of the following, choose the most appropriate answer (2pts each).

IS 0020 Program Design and Software Tools

For Teacher's Use Only Q No Total Q No Q No

COM S 213 PRELIM EXAMINATION #2 April 26, 2001

2 is type double 3 auto i = 1 + 2; // evaluates to an 4 integer, so it is int. 1 auto d = 5.0; // 5.0 is a double literal, so it

Object Oriented Programming. Assistant Lecture Omar Al Khayat 2 nd Year

2 ADT Programming User-defined abstract data types

COMP 2355 Introduction to Systems Programming

Ministry of Higher Education Colleges of Applied Sciences Final Exam Academic Year 2009/2010. Student s Name

Lecture 2, September 4

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

Instantiation of Template class

Abstract Data Types (ADTs) 1. Legal Values. Client Code for Rational ADT. ADT Design. CS 247: Software Engineering Principles

Discussion 1E. Jie(Jay) Wang Week 10 Dec.2

C++: Overview and Features

Introduction to C++ Systems Programming

Due Date: See Blackboard

Polymorphism Part 1 1

An Object Oriented Programming with C

Use the dot operator to access a member of a specific object.

Chapter 1 Getting Started

COMP322 - Introduction to C++ Lecture 01 - Introduction

CSE 374 Programming Concepts & Tools. Hal Perkins Spring 2010

Introduction to Computer Science Midterm 3 Fall, Points

Pointers, Dynamic Data, and Reference Types

Lecture on pointers, references, and arrays and vectors

OOPS Viva Questions. Object is termed as an instance of a class, and it has its own state, behavior and identity.

EE 355 Unit 10. C++ STL - Vectors and Deques. Mark Redekopp

CS 247: Software Engineering Principles. ADT Design

CSCE 206: Structured Programming in C++

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

Paytm Programming Sample paper: 1) A copy constructor is called. a. when an object is returned by value

Where do we go from here?

ComS 228 Exam 1. September 27, 2004

Note 12/1/ Review of Inheritance Practice: Please write down 10 most important facts you know about inheritance...

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

Object-Oriented Programming (OOP) Fundamental Principles of OOP

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

Preface... (vii) CHAPTER 1 INTRODUCTION TO COMPUTERS

Agenda. The main body and cout. Fundamental data types. Declarations and definitions. Control structures

C++ Crash Kurs. Polymorphism. Dr. Dennis Pfisterer Institut für Telematik, Universität zu Lübeck

This is a CLOSED-BOOK-CLOSED-NOTES exam consisting of five (5) questions. Write your answer in the answer booklet provided. 1. OO concepts (5 points)

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

PIC 10A Objects/Classes

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

ANSI C. Data Analysis in Geophysics Demián D. Gómez November 2013

Assumptions. History

CS201 Latest Solved MCQs

Overloading Operators in C++

More Advanced Class Concepts

Data type of a pointer must be same as the data type of the variable to which the pointer variable is pointing. Here are a few examples:

AN OVERVIEW OF C++ 1

Variables. Data Types.

Problem Solving with C++

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

Transcription:

CS 211 Winter 2004 Sample Final Exam (Solutions) Instructor: Brian Dennis, Assistant Professor TAs: Tom Lechner, Rachel Goldsborough, Bin Lin March 16, 2004 Your Name: There are 6 problems on this exam. Each one is worth 20 points. They are not all of equal difficulty. Please read all of them before starting and attempt the least difficult first. You have 120 minutes to complete the exam. When time is up, please stop writing and turn in your quiz. If you have to be asked to stop you will receive no credit for the question you are working on. Problem 1 Problem 2 Problem 3 Problem 4 Problem 5 Problem 6 Total 1

Problem 1 10 Points. Explain why a static member function of a class shouldn t try to access a this variable. Static member functions are intended to be class wide and not specific to a particular instance. Thus, they actually never get a this pointer. Most compilers will catch this as a syntax error. 10 points. Briefly give and explain one positive aspect and one negative aspect of operator overloading in C++. Overloaded operators are good in that we can use standard, terse, operator syntax for operations on datatypes that it makes sense. For example, manipulations on a matrix datatype might be done using overloaded operators as opposed to verbose member function calls. The downside of overloaded operators is that they don t actually have to conform to the implied semantics of the operator. For example, we could have a + operator that implements subtraction. Overloaded operators provide an easy opportunity to write obfuscated code. 2

Problem 2 ---------------------------------------------------------- // classes.h class Base { public: Base(); virtual void howdy(); void doody(); private: //... ; class Derived : public Base { public: Derived(); virtual void howdy(); void doody(); private: //... ; ------------------------------------------------------- // base.cpp #include <iostream> #include "classes.h" using namespace std; //... void Base::howdy() { cout << "Let s get ready to CS rumble!" << endl; ; void Base::doody() { cout << "I think I m going to finish early." << endl; ; ---------------------------------------------------- // derived.cpp #include <iostream> #include "classes.h" using namespace std; //... void Derived::howdy() { cout << "I hope you were the groom!" << endl; void Derived::doody() { cout << "Ted Nugent called. He wants his shirt back." << endl; 3

Assuming the code on the previous page, for each of the numbered lines below indicate what is printed out (2 points) and give a brief explanation (3 points). // ------------------------------------------ int main(int argc, char **argv) { Derived dr; Base& br = dr; Base* bp = new Derived; dr.howdy(); // 1 br.doody(); // 2 bp->howdy(); // 3 bp->doody(); // 4 I hope you were the groom! // 1 I think I m going to finish early. // 2 I hope you were the groom! // 3 I think I m going to finish early. // 4 4

Problem 3 On the next few pages is code for an integer IntSet class that is derived from vector<int>. Write 4 member functions for the class. A new constructor that takes an array of integers and an integer count, and initializes the IntSet to hold the integers in the array A union member function that takes another IntSet and returns a new IntSet which has the elements of both sets. An intersection member function that takes another IntSet and returns a new IntSet which has all elements which are in both sets. A difference member function that takes another IntSet s and returns a new IntSet which contains the elements that don t appear in s // Since arrays and pointers are interchangeable, the preexisting // IntSet::IntSet(int* vals, int cnt) constructor is fine. IntSet IntSet::set_union(IntSet is) { IntSet newset(*this); // Can t use bracket operator since we overloaded it for (int i = 0; i < is.size(); i++) newset.add(is.at(i)); return newset; IntSet IntSet::set_intersection(IntSet is) { IntSet newset; vector<int>::iterator ix = is.begin(); while (ix < is.end()) { if (is_member(*ix)) newset.add(*ix); ix++; return newset; IntSet IntSet::set_difference(IntSet is) { IntSet newset(*this); for (int i = 0; i < is.size(); i++) { if (is_member(is[i])) newset.del(is[i]); return newset; 5

#ifndef _INT_SET_H_ #define _INT_SET_H_ 1 #include <iostream> #include <vector> using std::vector; using namespace std; // This class inherits from the template class // vector<int> so it s an ordered collection of integers // vectors are optimized for adding new elements to the end. class IntSet : public vector<int> { public: // Create an empty set IntSet(); // Initialize a set from, an array of integers IntSet(int* ints, int cnt); // Test whether i is in the set bool is_member(int i); // Add an integer to the set void add(int i); // Delete an integer from the set void del(int i); // Test whether idx is in the set bool operator[](int idx); friend ostream& operator<<(ostream& os, IntSet& is); private: ; ostream& operator<<(ostream& os, IntSet& is); #endif 6

#include <iostream> using namespace std; #include "IntSet.h" // Nothing really exciting here, other than using // submember initialization IntSet::IntSet() : vector<int>() { // Since I m a vector<int> and I know that the vector<int> // part of an IntSet has already been initialized, it s safe // to call the push_back member function IntSet::IntSet(int* ints, int cnt) { for (int i = 0; i < cnt; i++) { if (!is_member(ints[i])) { push_back(ints[i]); // Again, an example of using inherited member functions directly // size, and at which are defined in vector<int> bool IntSet::is_member(int i) { for (int j = 0; j < size(); j++) { if (i == at(j)) return true; return false; void IntSet::add(int i) { if (!is_member(i)) { push_back(i); // vectors provide iterators to iterate sequentially // through their elements. You can also delete elements // from the collection using an iterator void IntSet::del(int i) { vector<int>::iterator ix = begin(); while (ix < end()) { if (*ix == i) { erase(ix); return; ix++; return; 7

// This can t be used on the left hand side of an assignment // since it doesn t return a reference type. bool IntSet::operator[](int idx) { return is_member(idx); // This doesn t actually have to be a friend of the // IntSet class since it doesn t use any private members ostream& operator<<(ostream& os, IntSet& is) { os << "BitSet["; for (int i = 0; i < is.size(); i++) { os << is.at(i) << " "; os << "]"; return os; 8

Problem 4 #ifndef _CONS_H_ #define _CONS_H_ 1 #include <string> using namespace std; class OurString { public: // added friend ostream& operator<<(ostream& os, OurString& ostring); OurString(char* null_string); OurString(char c); int len(); int set_char(int index, char c); OurString reverse(); // added private: string s; // int buf_cnt; // char* buf; ; ostream& operator<<(ostream& os, OurString& ostring); // added #endif 10 points. The above OurString class is intended to represent a sequence of charcters that can hold any character including \0. buf_cnt represents the number of characters currently in the string. buf is completely private storage of an OurString instance s characters. Rewrite the class so that it uses the builtin string class in a has-a relationship. Change the class declaration and write implementations for all of the declared member functions. #include "OurString.h" OurString::OurString(char* null_string) : s(null_string) { OurString::OurString(char c) : s() { s += c; int OurString::len() { return s.size(); int OurString::set_char(int index, char c) { char old_c = s[index]; s[index] = c; return old_c; 9

10 points. Add two functions to the OurString class. A reverse function that returns a reversed OurString and an overloaded output operator for OurStrings. OurString OurString::reverse() { OurString new_string(""); for (int i = s.size() - 1; 0 <= i; i--) { new_string.s += s[i]; return new_string; ostream& operator<<(ostream& os, OurString& ostring) { os << ostring.s; return os; 10

Problem 5 10 points Give two reasons, with brief explanations, why polymorphic functions are better than using switch statements in classes. One, programmers don t have to hunt down and change the source code for the switch statement if a new type of object is to be handled by the dynamic dispatch supported by polymorphic functions. In some cases, the programmer may not even have the source code to change. Second, using switches tightly couples the derived and base classes, since the base class has to know about the derived classes. With polymorphic functions, the base class defines an interface, but doesn t have to know of any derived classes that implement it. 10 points Briefly explain what a pure virtual function is and why they re important. Also, give a brief code example of declaring one. A pure virtual function is declared like so: class Foo {... void virtual foo_function() = 0;... This forces the class Foo to be an abstract base class. No instances of this class can be created. Derived classes can be declared and instances of these classes created if they override and implement foo_function. The pure virtual function forces derived classes to support a particular procedural interface. 11

Problem 6 For each of the following statements indicate wheter it is true or false (2 points) and give a brief explanation (2 points). By default, C++ member functions are polymorphic. False. We have to use the virtual keyword to get polymorphic behavior for member functions. Only pointers allocated using new can be deleted True. delete reclaims space dynamically allocated from the heap. Pointers to stack objects or global objects are automatically managed by the C++ runtime. Template functions have to be member functions. False. We could write a standalone templated version of square that operated on arithmetic types. A compiler analyzes a program, builds an internal representation of the program, and immediately executes the program s actions. False. An interpreter executes the actions immediately. A compiler takes the internal representation and generates binary representation to be executed later. In C++ we can only overload binary operators False. We can overload some unary operators such as!. 12