CS 116 Midterm 1

Ace your homework & exams now with Quizwiz!

how do you write a constructor

class Coin { private: string denomination; bool headsUp; int coinValue; public: Coin(string denomination); //constructor string getDenomination() const; void flip(); bool isHeadsUp() const; int value() const; }

negations operators

!a, -a, ~a

What is encapsulation?

"the process of packaging/wrapping your program, diving each of its classes into 2 distinct parts: the interface and the implementation" / encapsulation involves combining similar data and functions into a single unit called a class.

What's the reference operator to get the memory address of a variable

& (ex. &num)

address of operators

&a

How do you use constructors

1. Declare 2. Decline 3. Call

What is a virtual function?

A function that can be redefined in a derived class (overridden)

Implement a template class "Box" that can hold an "item" of any data type and provide methods to set and get the item.

Box.h template <typename T> class Box { public: void setItem(const T& newItem); T getItem() const; private: T item; }; Box.cpp template <typename T> void Box<T>::setItem(const T& newItem) { item = newItem; } template <typename T> T Box<T>::getItem() const { return item; }

What should you ALWAYS do when you are going to end a program that has this (*)

Delete and make it a nullpointer

indirection operators

*a

What is used when the relationship is a "is-a" relationship (tree is a plant)

Inheritance (arrow used)

What is the difference between inheritance and composition

Inheritance: "is a" Composition: "has a"

Which of the following statements is correct about an accessor member function? It modifies one or more data members of an object. It returns the value of a data member of an object but does not modify any data member values. It is only called by other member functions of an object. It cannot be declared with the keyword const.

It returns the value of a data member of an object but does not modify any data member values.

Mutator functions/Accessor functions (which are setters/getters?)

Mutators: setters Accessors: getters

What does a constructor do?

Sets up the initial state of an object

class Counter { public: Counter(int new_count); void add_counter(int new_counter); void display(); private: int counter; }; Counter::Counter(int new_count) { counter = new_count; } void Counter::add_counter(int new_counter) { counter = counter + new_counter; } void Counter::display() { cout << "The count is " << counter; } class DoubleCounter : public Counter { public: DoubleCounter(int new_count); void add_counter(int new_counter); }; DoubleCounter::DoubleCounter(int new_count) : Counter(new_count * 2) { } void DoubleCounter::add_counter(int new_counter) { Counter::add_counter(new_counter * 2); } int main() { DoubleCounter counter = DoubleCounter(10); counter.add_counter(5); counter.display(); return 0; } cout is:

30

What does the following code print? int x = 4; cout << ++x << x << x++ << x; 5556 4567 5566 None of these

5556

Which one of the following is an example of the "substitution principle"? A derived class object can be used in place of a base-class object. A derived class object must be used in place of a base-class object. A base-class object can be used in place of a derived class object. A base-class object must be used in place of a derived class object.

A derived class object can be used in place of a base-class object.

A template in C++ is what? A vector, stack, set, map, priority_queue, or queue data structure A function or class which at compile time can be fitted to various data types, such as int or double or string Standard formatting rules for common C++ code blocks, such as functions and classes A preformatted code block that can be plugged into a program

A function or class which at compile time can be fitted to various data types, such as int or double or string

What is a pure virtual function?

A function that MUST be implemented by a derived class (overridden)

What is a member function?

A function that is defined by a class and operates on objects of that class (also called a method)

What's a constructor?

A member function that can be used to make more objects of that class

Explain how abstract classes facilitate polymorphism in C++. Illustrate your answer with a short code example.

Abstract classes use at least one pure virtual function. Because of this, they help facilitate polymorphism by allowing different derived classes to access the function from the base class. It helps facilitate polymorphism since the function can be used for different reasons without making new functions in every class. classs Chip { public: virtual string spread() const = 0; virtual ~Chip() = 0; }; class Salsa : public Chip { public: string spread() const override; };

How do you make a virtual function pure, and how do you use it in a derived class?

Add =0 to make a virtual function pure

An object of a class may have which of the following items? Data members Mutator member functions Accessor member functions All of the listed items

All of the listed items

What's an interface?

An interface is like a class in which none of the methods have been implemented—the method signatures are there, but the body of each method is empty. They are the properties and methods of an object.

What is an abstract class

Any class that has a pure virtual function

The purpose of inheritance is to model similar objects which have different: Data values Behaviors Public vs. private functions All of these

Behaviors

Study the following class interface for the class CashRegister: class CashRegister { public: void set_item_count(int count); void view() const; void view_count() const; CashRegister(); CashRegister(int item_count); CashRegister(double cash_balance); CashRegister(int item_count, double cash_balance); private: int item_count1; double cash_balance1; }; Which of the following constructors is called for the object declaration CashRegister c1(10, 100)? CashRegister() CashRegister(int item_count) CashRegister(double cash_balance) CashRegister(int item_count, double cash_balance)

CashRegister(int item_count, double cash_balance)

How do make a class that inherits from another class? Class truck ; public vehicle {} Class iron, private metal() Class dumping + public asianFood() Class student, private schoolPeople() None

Class student, private schoolPeople()

What is used when the relationship is a "has a" relationship (tree has a leaf)

Composition (diamond used)

For any custom class that dynamically allocates memory, what member functions must be supplied? Constructor, destructor, operator= Copy constructor, destructor, operator= Copy constructor, destructor Copy constructor, constructor, destructor

Copy constructor, destructor, operator=

Define what a pure virtual function is. How does declaring a pure virtual function in a class make it abstract? Give an example of the C++ header code that includes a pure function.

Correct A pure virtual function is a function that is overridden in a derived class and is declared by assigning a zero specifier in a base class. It makes the class abstract since it allows it to be used in classes that derive from it. register.h class Register { public: virtual string info() const = 0; string display(string text); private: string text; };

Some programmers are careful about using this within member functions to make clear the distinction between: Parameter variables and local variables Parameter variables and global variables Private data members and public data members Data members and other variables

Data members and other variables

The __ inherits some or all of the properties of the __ class

Derived, base

What is the term for the function in a C++ class definition that can de-allocate dynamic memory when the object goes out of scope, as in a return from a function which has created a local object? Tilde function Deconstructor (Like Professor Raupach was taught) Destructor Exit

Destructor

The purpose of inheritance is to model objects with ______

Difference behavior

The reserved word virtual is used with a base-class member function to alert the C++ compiler that it must determine the actual member function to call at run-time. Thus derived classes can have their own (possibly completely different) versions of the base-class function. When a base-class defines a member function to be virtual, what should each derived class do? Derived classes need to do nothing further Each derived class should over-ride the virtual base-class function so that it defines a function with the same name that is unique to the derived class Derived classes should invoke the base-class virtual function Derived classes should only be used as array elements

Each derived class should over-ride the virtual base-class function so that it defines a function with the same name that is unique to the derived class

Given a Single Linked List like the one above built with the Node struct provided, write the c++ code to safely create and insert the value 8 between the values of 7 and 3.

Graded Node* newNode; newNode->data = 8; newNode -> next = nullptr; newNode-> next = head->next->next->next; head->next->next = newNode;

What is encapsulation

Hiding data and implementation details within a class

How to make UML

How to make UML (- for private, + for public) Trip (class name) +Trip() : None +Trip(string, string, string) : None - departure : string - title : string - destination : string +getDeparture() : string +setDepature(string) : void +getTitle() : string +setTitle(string) : void +getDestination() : string +setDestination(string) : void

Polymorphism implementation depends upon which of the following? I.Virtual member functions II.Class inheritance III.Function overloading I only II only III only I, II, and III

I, II, and III

Consider the code snippet below: class ChoiceQuestion : public Question { public: void display() override; . . . }; What is the meaning of the override in the last line? I. It forces this function to override Question::display(). II. It indicates this function should override Question::display(), and will cause a compiler error if it does not. III. It indicates the the Question::display() must be call in ChoiceQuestion::display(). I only II only III only II and III

II only

Explain the concepts of composition and aggregation in C++. How do they differ in terms of ownership and lifetime of objects?

In C++, composition is when a class owns or contains another class, and aggregation is when a class uses references and/or pointers to get objects of another class. They differ in ownership and lifetime of objects since in composition, the object that is owned by its base/owned class cannot exist on its own. In aggregation, the object that is owned by its base/owned class can exist if the object of owning class does not exist.

The process in which subclass inherits functions from parent classes is called what?

Inheritance

What is the relationship between a base class and a derived class called? Polymorphism Encapsulation Aggregation Inheritance

Inheritance

When discussing relationships between two classes, what is the difference between inheritance and aggregation? Inheritance specifies an "is-a" relationship; aggregation specifies a "has-a" relationship Inheritance specifies a "has-a" relationship; aggregation specifies an "is-a" relationship Inheritance specifies a "containment" relationship; aggregation specifies "polymorphism" Inheritance specifies "polymorphism"; aggregation specifies an inheritance relationship

Inheritance specifies an "is-a" relationship; aggregation specifies a "has-a" relationship

What's a constructor's job

It initializes a class (all properties should be initialized)

What is true about a mutator member function? It modifies one or more data members of an object. It returns the value of a data member of an object but does not modify any data member values. It is only called by other member functions of an object. It must be declared with the keyword const.

It modifies one or more data members of an object.

What's a pointer

It's a variable with a memory address with a particular type of data type

What is implementation?

It's when the interface is being implemented

The virtual reserved word can be used for which of the following? Member functions (Methods) Data members (Properties) Constructors All the listed items

Member functions (Methods)

You have been asked to design an application for a music store. Which of the following options would be appropriate to be defined as classes in this application? MusicRecording, MusicTrack, and PlayMusic CalculateMusicPrice, PlayMusicRecording, and PurchaseMusicRecording MusicRecording, MusicTrack, and MusicCollection None of the listed items

MusicRecording, MusicTrack, and MusicCollection

what is the difference between OOP and procedural programming

OOP has abstract data types

Suppose you design an inheritance hierarchy with the following classes: Crocodile, Alligator, Reptile, and Turtle. Which of these is the base class? Crocodile Reptile Turtle Alligator

Reptile

If you do not define a destructor function for your custom class: The C compiler defines a default destructor for you Your class may leave memory leaks from strings and vectors used as data members It is OK as long as your class doesn't dynamically allocate memory with new All of these

The C compiler defines a default destructor for you

What is a class?

The code you write to define an object (blueprint)

What's an inheritance relationship?

The derived (child) class points and inherits data/behavior from the base (parent) class. Inheritance is reusing/extending existing classes without modifying them

How should base-class data members be referenced and used from derived classes? The derived class should re-define the data member using the same name The derived class should use base-class accessors and mutators as a way to access or update base-class data members The derived class should re-define the data member but use distinct names Derived classes cannot use base-class data members

The derived class should use base-class accessors and mutators as a way to access or update base-class data members

Imagine you are developing a weather application. In this weather application your are going to have an class for a "Location" the location has 4 properties: zip code, temperature, humidity, precipitation. So the user can look up the weather in their area. Below type in the class declaration (the part that goes in the .h) of the Location application with accessors and mutators for each property. You can assume: - The zip codes are united states only, not international - Precipitation and humidity are recorded as percentages. - Temperature is in fahrenheit. You don't need to comment the code. Your code does not need to be compiler perfect but it should demonstrate that you understand class definitions as getters/setters.

class Location{ private: int zipCode; double temperature; double humidity; double precipitation; public:Temperature();Temperature(double zipCode, double Temperature, double humidity, double precipitation); int getZipCode() const; void setZipCode(double zipCode); double getTemperature()const; void setTemperature(double temperature); double getHumidity() const; void setHumidity(double humidity); double getPrecipitation() const; void setPrecipitation(double precipitation); }

Is a car and steering wheel composition or inheritance

composition (has-a relationship)

multiplicative operators

a/b, a*b, a%b

shift operators

a<<1, b>>2

relational operators

a<b, a>=b, a==b, a!=b

assignment operator

a=b

What is the correct way to call the accelerate(10) function on car1? class Car { public: Car(double speed); void start(); void accelerate(double speed); void stop(); double get_speed() const; private: double speed; }; Car::Car(double speed) { this->speed = speed; } void Car::start() { speed = 1; } void Car::accelerate(double speed) { this->speed = this->speed + speed; } void Car::stop(){ speed = 0; } double Car::get_speed() const { return speed; } int main() { Car* car1 = new Car(100); // What is the correct way to call the accelerate(10) function on car1? return 0; }

car1->accelerate(10);

What's a method

functions in a class

Which of the following function declaration would you add the const suffix to? setName(string name); getName(); Person(string name, string hairColor); Person();

getName();

Where are dynamic variables stored?

heap (freestore) memory

Is a dog and animal composition or inheritance

inheritance (is-a relationship)

How do you declare a pointer

long *bob = 5; / long* bob = 5

Why do we study OOP

maintainable, models the real world, modular and reusable, allows big teams to work together, objects are more testable

Is this cookie class declared correctly? class Cookie { private: string shape; String toppings; int calories; Public: cookie(shape, toppings, calories); };

no ; need string shape, string toppings

Binary operators

perform actions with two operands

Unary operators

perform an action with a single operand

Which methods should be public/private: SocialSecurityNumber: String gender: boolean getSocialSecurityNumber: String getGender: boolean setSocialSecurityNumber: String setGender: boolean

private: SocialSecurityNumber: String gender: boolean public: getSocialSecurityNumber: String getGender: boolean setSocialSecurityNumber: String setGender: boolean

A class can have ______ constructor function(s) and ______ destructor function(s). one, one several, several one, several several, one

several, one

Consider the code snippet below, where the Circle and Rectangle objects are both derived classes from the base class Shape: int main() { Shape* shapes[NUM_OBJECTS]; shapes[0] = new Circle(0, 0, 100, 150); shapes[1] = new Rectangle(200, 200, 50, 100); shapes[2] = new Circle(300, 50, 250, 250); shapes[3] = new Rectangle(100, 350, 200, 150); for(int i = 0; i < NUM_OBJECTS; i++) { // Below enter the code that will call display on all the objects in shapes } }

shapes[i]->display();

class Cheetah { public: void set_speed(double new_speed); private: double speed; }; void Cheetah::set_speed(double new_speed) { speed = new_speed; } int main() { Cheetah ch1; ch1.set_speed(144); cout << "Cheetah speed: " << ch1.speed; return 0; } This code will not compile, why?

speed is set as a private, so it cannot be brought up in main

Where are ordinary variables stored?

stack memory

What is polymorphism?

the same entity (function or object) behaves differently in different scenarios / overriding

exception handling code example

try { int a = 0; int b = 0; cout << "Enter 2 num to get quotient" << endl; cin >> a >> b; if (b == 0) { throw domain_error("You can't divide by 0!"); } double c = (double) a / b; cout << "The quotient of " << a << "/" << b << " is " << c << endl; } catch (logic_error error) { cerr << error.what(); } }

colprof.h class colprof: Employee { vector c; string n; public: void add(string); string print(); //overrides Employee void Name(string); string Name(); }; colprof.cpp string colprof::Name() { return n; } void colprof::Name(string value) { n = value; } void colprof::add(std::string data) { c.push_back(data); } string colprof::print() { string it; for(auto cs: c) {it += (cs + '\n');}; return it; } main.cpp using namespace std; int main() { colprof *n = new colprof(); n->Name("Paul Raupach"); n->add("CS102"); n->add("CS113"); n->add("CS116"); n->add("cs124"); cout << n->Name() << endl << n->print(); return 0; } Above is perfectly functioning code for a class that tracks professors and their classes. What are 5 things you'd do to improve it's readability, maintainability and/or stability?

1. Do CamelCase or underline after each word 2. Don't use letters like 'n' to declare variables (we don't know what n means) 3. tab after using semicolons (in colprof.cpp) 4. add comments in the header to clarify confusing parts 5. indent in the header (void add(string);string print(); //overrides Employeevoid Name(string);string Name();) should not be on the same line as public: 6. Add documenting comments for functions

what are the 4 fundamental concepts of object oriented programming

1. encapsulation 2. inheritance 3. polymorphism 4. composition

What are examples of exception-handling constructs

1. try block (exited immediately if a throw statement executes) 2. throw statement (if reached, execution jumps immediately to the end of the try block) 3. catch clause (executes to catch the thrown exception)

How do you call by reference (what do you call)

The memory address, not the variable name, is passed into functions

What if anything is wrong with the following class definition? class Fraction //represents fractions of the type 1/2, 3/4, 17/16 { public: Fraction(int n, int d); Fraction(int n); Fraction(); double operator+(Fraction other) const; double operator-(Fraction other) const; double operator*(Fraction other) const; bool operator<(Fraction other) const; void print(ostream& out) const; // other member functions exist but not shown private: int numerator; int denominator; }; The operator functions for +, - and * should return type Fraction Not all the constructors are needed It is missing a private double data member to represent the decimal value of the fraction Nothing is wrong

The operator functions for +, - and * should return type Fraction

Given the following C++ classes, identify whether the relationships between them are examples of composition or aggregation. Justify your answers. class Engine { // Engine class definition }; class Car { Engine engine; // Car class definition }; class Driver { Car* car;

The relationship between Engine and Car is an example of composition. Car has engine as an object, taking it directly from the class such as in "Engine engine." Engine would have to exist for the object in Car to keep existing. The relationship between Car and Driver is an example of aggregation. Driver uses a pointer to refer to the object "car" such as in "Car* car." This method is used within aggregation.

What's a dynamic variable

They are created and destroyed while the program is running. They are created using pointers and the "new" operator

What is the reason for including the #ifndef, #define, and #endif in the header file Animal.h? #ifndef ANIMAL_H #define ANIMAL_H class Animal { public: Animal(); Animal(double new_area_hunt); double get_area_hunt() const; private: double area_hunt; }; #endif It is standard boilerplate code, like using namespace std; that must be in all header files. They define the interface for the class. They are used to avoid compiler errors from duplicate definitions.

They are used to avoid compiler errors from duplicate definitions.

What are exception-handling constructs

They keep error-checking code separate and to reduce redundant checks

What is the purpose of operator overloading in programming? To eliminate the need for standard operators altogether. To increase code complexity and make it harder to understand. To restrict the use of operators to built-in data types only. To allow the use of standard operators with custom data types, providing a natural andintuitive syntax.

To allow the use of standard operators with custom data types, providing a natural and intuitive syntax.

Why are templates used in C++? To avoid writing separate but nearly identical code for various data types To properly format code for viewing by other programmers To properly implement most classes All of the above

To avoid writing separate but nearly identical code for various data types

class Vector2D { private: int x, y; public: Vector2D(int x, int y); // add operator overloading for +, ++ (pre and post) = and == }; #endif //VECTOR2D_H Vector.cpp #include "Vector2D.h" Vector2D::Vector2D(int x, int y) { this->x = x; this->y = y; } Above is the start of a 2D Vector class with x and y properties. Below write the C++ Implementation for overloading the addition (+), both pre and post Increment (++), assignment (=) and equivalence (==) operator. addition should add two 2D vectors together by adding the x and y properties of each vector increment should add 1 to both x and y assignment should set on 2D vector equal to anther two 2D vectors are equal if they have equal x and y properties

Vector.cpp // addition Vector2D Vector2D::operator+(const Vector2D& other) const { return Vector2D(this->x + other.x, this->y + other.y); } //pre and post increment Vector2D& Vector2D::operator++() { ++x; ++y; return *this; } Vector2D Vector2D::operator++(int dummy) const{ Vector2D temp(*this); ++(*this); return temp; } // assignment (=) Vector2D& Vector2D::operator=(const Vector2D& other) { this->x = other.x; this->y = other.y; return *this; } // equivalence bool Vector2D==(const Vector2D other) const { return (this->x == other.x && this->y == other.y); }

When should you use the const keyword

When calling the method will not change the state of an object. If the const keyword is used, then it is an accessor/getter. If not, then it might be a mutator/setter.

what's a vector

a dynamic array that can grow or shrink in size; A vector in C++ is like a flexible container that can hold a bunch of items. You can put things in it, take them out, and the container adjusts its size automatically. It's like having a magical bag that can change its size to fit whatever you want to put inside.

logical operators

a&&b, a||b

bitwise operators

a&b, a|b, a^b

assignment operators

a++, ++a, --a, a--

additive operators

a+b, a-b


Related study sets

NURS 482 - Exam 1 Practice Questions (Module 1-2)

View Set

Chapter 4 Installing and Configuring the Dynamic Host Configuration Protocol

View Set

What is a partnership and how does it work

View Set