Termbank
  1. A
    1. API
    2. ASAN
    3. Access specifiers
  2. C
    1. Constructor
    2. const
  3. G
    1. GDB
    2. g++
  4. M
    1. Make
    2. Memory Leak
  5. P
    1. Pointer
  6. R
    1. Recursion
  7. S
    1. std
  8. V
    1. Valgrind
Completed: / exercises

Instructions

THIS IS A PRACTICE EXAM ONLY, THE GRADE YOU GET FOR THIS EXAM IS NOT USED IN YOUR FINAL GRADE CALCULATION FOR THIS COURSE.
This mock exam will help you understand the difficulty you can expect on the real final exam.

Exam Rules

Good luck!

1. Classes, struct, constructors

Question 1

What is the result of compiling and executing the following code?
A. 2 sent to standard out.
B. The code results in a compile error.
C. The code results in a runtime error.
D. The code has undefined behavior.
E. None of the above describes the execution of this function.
Warning: You have not logged in. You cannot answer.

Question 2

Consider the following class Gadget and its use in the client main() function:
What should the constructor for the class Gadget for the code to compile and run with no warnings, producing the following standard out output?
Gadget: Gadget, ID: 1
Gizmo: Gizmo, ID: 2
A. Gadget(std::string n, int i) : name(n), id(++i) {}
B. Gadget(std::string n, int &i) : name(n), id(i++) {}
C. Gadget(std::string n, int i) : name(n), id(i++) {}
D. Gadget(std::string n, int &i) : name(n), id(++i) {}
E. None of the above
Warning: You have not logged in. You cannot answer.

2. .cpp/.h, encapsulation

Question 3

Consider the following code:
Which of the following should replace /* LINE */ so that the code compiles and runs with no warnings and with Unicorn: Sparkle sent to standard out?
A. sparkleUnicorn.name
B. sparkleUnicorn->name
C. Unicorn.getName()
D. Unicorn->name
E. None of the above.
Warning: You have not logged in. You cannot answer.

Question 4

Consider the following code:
Which of the following is the correct function definition for the member function getModelName outside of the VRHeadset class in place of // LINE?
A. std::string getModelName() const { return modelName; }
B. std::string VRHeadset::getModelName() const { return modelName; }
C. std::string VRHeadset::getModelName() { return modelName; }
D. std::string VRHeadset::getModelName(std::string model) const { return modelName; }
E. std::string getModelName(std::string model) const { return modelName; }
Warning: You have not logged in. You cannot answer.

Question 5

Consider the following ChuChuTrain.h and ChuChuTrain.cpp files:
//the header file
#ifndef CHUCHUTRAIN_H
#define CHUCHUTRAIN_H

#include <string>

class ChuChuTrain {
public:
    ChuChuTrain(std::string model, int power);
    int getPower() const;
    void updatePower(int newPower);

private:
    std::string model;
    int power;
};

#endif
//the source file
#include "ChuChuTrain.h"

ChuChuTrain::ChuChuTrain(std::string m, int p) : model(m), power(p) {}

int ChuChuTrain::getPower() const {
    return power;
}

void updatePower(int newPower) {
    power = newPower;
}
Given this setup, identify the errors in the ChuChuTrain.cpp file:
A. The constructor ChuChuTrain::ChuChuTrain(std::string m, int p) is incorrectly defined.
B. The function int ChuChuTrain::getPower() const should not return power directly.
C. The function void updatePower(int newPower) is missing the class scope prefix and should be void ChuChuTrain::updatePower(int newPower).
D. The header file should not include the string library because it does not use std::string.
E. Both A and C
Warning: You have not logged in. You cannot answer.

3. Makefiles

Question 6

UPDATE: Option C needs to be reformulated. all answers were accepted.
Consider the following Makefile:
buildTool = ???
allBirds = owl penguin

all : birdAssembly
	buildTool

birdAssembly : allBirds
	buildTool

owl : nightVision sharpBeak
	buildTool

penguin : waterproofFeathers
	buildTool

sharpBeak : keratin
	buildTool
Assuming that buildTool correctly builds the target from the dependencies listed in the Makefile, which of the following is/are TRUE:
A. If all dependencies but sharpBeak exist in the directory, executing make will fail.
B. If all dependencies but keratin exist in the directory, executing make will fail.
C. Make will attempt to build the target birdAssembly before owl.
D. More than one of the above are true.
E. None of the above are true.
Warning: You have not logged in. You cannot answer.

Question 7

UPDATE, Option D needs to be reformulated. A and E were accepted as correct
Consider the following Makefile. It is fully functioning with no bugs.
CC = g++
CFLAGS = -O2 -Wall
LDFLAGS = -lm

SRC_DIR = src
OBJ_DIR = obj
EXECUTABLE = app

OBJECTS = $(OBJ_DIR)/main.o $(OBJ_DIR)/helper.o

all: $(EXECUTABLE)

$(EXECUTABLE): $(OBJECTS)
	$(CC) $(LDFLAGS) $(OBJECTS) -o $(EXECUTABLE)

$(OBJ_DIR)/main.o: $(SRC_DIR)/main.cpp
	$(CC) $(CFLAGS) -c $(SRC_DIR)/main.cpp -o $(OBJ_DIR)/main.o

$(OBJ_DIR)/helper.o: $(SRC_DIR)/helper.cpp
	$(CC) $(CFLAGS) -c $(SRC_DIR)/helper.cpp -o $(OBJ_DIR)/helper.o

clean:
	rm -f $(OBJECTS) $(EXECUTABLE)
Which of the following statements is/are TRUE about the above Makefile?
A. The all target compiles main.cpp and helper.cpp into object files in the obj directory and links them into an executable named app.
B. Running make clean will remove all object files, but not the executable or the source files.
C. The Makefile ensures the creation of the obj directory before compiling files.
D. The Makefile will not recompile anything as long as the corresponding object files are already present.
E. More than one of the above statements is true.
F. None of the above statements are true.
Warning: You have not logged in. You cannot answer.

4. Variables, memory, pointers, scope resolution

Question 8

What is the result of compiling and executing the following code?
A. 4, 5, 6 sent to standard out.
B. 4, 4, 6 sent to standard out.
C. 3, 3, 4 sent to standard out.
D. This code results in a compile error.
E. This code results in a runtime error
Warning: You have not logged in. You cannot answer.

Question 9

Consider the following code:
Which of the following should replace /* LINE 1 */ so that the code compiles and runs with no warnings and with 2 sent to standard out?
A. *y = &p;
B. *y = p;
C. **y = *p;
D. y = *p;
E. y = &p;
Warning: You have not logged in. You cannot answer.

Question 10

What is the result of compiling and running the following code?
A. The program incorrectly uses the delete operator, causing undefined behavior.
B. The pointer b is reassigned, causing the initial memory allocation to be lost without being freed.
C. The program outputs incorrect values due to improper initialization of the pointers.
D. The value assigned to b is never used before reassignment, suggesting redundant code.
E. Memory allocated to pointer a in line 4 is never released, leading to a memory leak.
F. There is a double deletion error when delete b is called.
Warning: You have not logged in. You cannot answer.

Question 11

UPDATE: Everyone got full points for this question.
The swap function does not work as expected. How should it be modified to correctly swap the values pointed to by a and b?
A. Replace int *tmp = a; with int tmp = *a;
B. Replace *b = *tmp; with *b = *a;
C. Replace int *tmp = a; with int tmp = b;
D. Replace *b = *tmp; with *b = tmp;
E. The pointers a and b should be passed by reference instead of by value: void swap(int *& a, int *& b) {...}
Warning: You have not logged in. You cannot answer.

5. Stack Heaps Arrays

Question 12

Consider the following code:
Which of the following should replace /* LINE */ so that the code compiles and runs with no warnings and with 1, 2 sent to standard out?
A. x[1] << ", " << x[2]
B. (*x)[1] << ", " << (*x)[2]
C. *x[1] << ", " << *x[2]
D. **x[1] << ", " << **x[2]
E. None of the above.
Warning: You have not logged in. You cannot answer.

Question 13

Consider the following incomplete code:
Your task is to complete the addCar function to add a new car with the given carID to the chuChuTrain vector. Ensure that the new car is added to the end of the chuChuTrain.
A.
int addCar(std::vector<TrainCar> train, int carID) {
    train.push_back(TrainCar(carID));
    return carID;
}
B.
void addCar(std::vector<TrainCar>& train, int carID) {
    train.push_back(&TrainCar(carID));
}
C.
void addCar(std::vector<TrainCar> train, int carID) {
    train.push_back(TrainCar(carID));
}
D.
void addCar(std::vector<TrainCar>& train, int carID) {
    train.push_back(TrainCar(carID));
}
E. None of the above
Warning: You have not logged in. You cannot answer.

6. ASAN, Valgrind

Question 14

Update: Both D and A were accepted.
Consider the following code in program1.cpp:
and program2.cpp:
Which one of the two programs has a runtime error, with the following message from ASAN:
==1==ERROR: AddressSanitizer: stack-use-after-return on address 0x799061e00060 
at pc 0x00000040143e bp 0x7fffa727cbf0 sp 0x7fffa727cbe8
A. Only 1.
B. Only 2.
C. Both 1 and 2.
D. Neither 1 nor 2.
Warning: You have not logged in. You cannot answer.

Question 15

This program contains a significant error. If compiled and run with an address sanitizing tool like ASAN or Valgrind, what kind of error could it report?
A. Buffer overflow error.
B. Memory leak detection.
C. Use of an uninitialized pointer.
D. None of the above would be detected by an address sanitizing tool.
E. All of the above.
Warning: You have not logged in. You cannot answer.

Question 16

This program contains a significant error. If compiled and run with ASAN, what kind of error would it most likely report?
A. ==1==ERROR: AddressSanitizer: heap-buffer-overflow on address
B. ==1==ERROR: AddressSanitizer: detected use of uninitialized value
C. ==1==ERROR: AddressSanitizer: attempting double-free on address
D. ==1==ERROR: UndefinedBehaviorSanitizer: undefined behavior
E. ==1==ERROR: LeakSanitizer: detected memory leaks
F. None of the above
Warning: You have not logged in. You cannot answer.

7. Parameter passing, return, const

Question 17

Consider the following code:
Which one of the following best describes the result of compiling and executing the above code?
A. 4 sent to standard out.
B. 7 sent to standard out.
C. 8 sent to standard out.
D. The code has undefined behavior because result goes out of scope.
E. None of the above.
Warning: You have not logged in. You cannot answer.

Question 18

What is the result of compiling and executing the following code?
A. 3, 1 sent to standard out.
B. 10, 1 sent to standard out.
C. The code does not compile.
D. The code results in a runtime error.
E. None of the above.
Warning: You have not logged in. You cannot answer.

Question 19

What is the result of compiling and executing the following code?
A. 1, 2 sent to standard out.
B. 2, 3 sent to standard out.
C. 2, 4 sent to standard out.
D. The code results in a compile error.
E. The code results in a runtime error, or it has undefined behavior because a and b go out of scope.
F. None of the above describes the execution of this code.
Warning: You have not logged in. You cannot answer.

Question 20

What is the result of compiling and executing the following code?
A. 3 sent to standard out.
B. 5 sent to standard out.
C. 6 sent to standard out.
D. This code does not compile.
E. None of these options is correct.
Warning: You have not logged in. You cannot answer.

Question 21

There is a bug in the following code, also provided to you at https://godbolt.org/z/9xvr71roq
Identify the line containing a critical bug. Once fixed, the output will be 100, 200. What line is it?
A. Line 6
B. Line 8
C. Line 10
D. Line 13
E. Line 15
F. None of the above.
Warning: You have not logged in. You cannot answer.

8. Copy constructor, destructor, operator overload

Question 22

RGBAPixel pixel1(225, 225, 225); // Line 1 
RGBAPixel * pixel2; // Line 2 
pixel2 = &pixel1; // Line 3 
Which of the following is true about the above three lines of code? Assume that RGBAPixel class has appropriately defined all of the following four: a 3-parameter constructor RGBAPixel(int x, int y, int z), a copy constructor, a destructor, and an overloaded assignment operator.
A. Line 2 creates a variable on the stack.
B. Line 2 creates a variable on the heap.
C. Line 3 causes a segmentation fault.
D. Line 3 uses the operator= function defined in the RGBAPixel class.
E. More than one statement above is true.
Warning: You have not logged in. You cannot answer.

Question 23

Choose one statement that is true about the result of compiling and executing the following code?
A. The string cold coffee was consumed is sent to standard out once.
B. The string cold coffee was consumed is sent to standard out twice.
C. The string cold coffee was consumed is not sent to standard out.
D. The code results in a compile error.
E. The code results in a runtime error.
Warning: You have not logged in. You cannot answer.

Question 24

Consider the following code:
What is the correct way to define the function operator + in the Unicorn class to allow two Unicorn objects to be added together, so that the above code compiles and runs with 30 sent to standard out?
A. Unicorn operator+(const Unicorn& other)
B. Unicorn operator+(const Unicorn* other)
C. Unicorn& operator+(Unicorn& other)
D. Unicorn& operator+(Unicorn other)
E. Unicorn* operator+(Unicorn* other)
Warning: You have not logged in. You cannot answer.

9. Inheritance, virtual functions, abstract classes

Question 25

Assume that all of the constructors, destructors and member functions are well implemented and result in a code with no compile or runtime errors.
Which one of the following statements is true?
A. Both Drink() constructor and getSnack can make the assignment isWarm = true.
B. Both Drink() and Coffee() constructors can make the assignment calories = 200.
C. Both Coffee() constructor and getSnack can make the assignment isWarm = true, but Drink() constructor cannot.
D. Drink() constructor can make the assignment calories = 200, but Coffee() constructor cannot.
E. More than one statement above is true.
Warning: You have not logged in. You cannot answer.

Question 26

Which one is true about the result of compiling and executing the following code?
A. The string coffee was consumed sent to standard out once.
B. The string coffee was consumed sent to standard out twice.
C. The string coffee was consumed is not sent to standard out.
D. The code results in a compile error.
E. The code results in a runtime error.
Warning: You have not logged in. You cannot answer.

Question 27

Consider the following code involving two classes, Unicorn and BabyUnicorn, in which BabyUnicorn inherits from Unicorn. The Unicorn class has a constructor that requires an integer argument, whereas BabyUnicorn has a no-argument constructor.
There is a problem with the code, which one is it?
A. The code compiles and outputs Magic Power: 0
B. The code results in a compile error due to the lack of an appropriate no-argument constructor in the Unicorn class.
C. The code results in a runtime error because the BabyUnicorn class does not initialize its parent class properly.
D. The code compiles successfully, but does not run due to a segmentation fault.
E. None of the above describes the problem.
Warning: You have not logged in. You cannot answer.

Question 28

Consider the pure virtual class Holiday, and Vappu class inherited from Holiday.
Which of the statements is true about the assignment fullnessFactor += change;?
A. Both Vappu::eat and Vappu::drink can make the assignment.
B. Neither Vappu::eat nor Vappu::drink can make the assignment.
C. Vappu::eat can make the assignment, but Vappu::drink cannot.
D. Vappu::drink can make the assignment, but Vappu::eat cannot.
E. The answer to this question cannot be determined from the given code.
Warning: You have not logged in. You cannot answer.

10. Templates, generic programming

Question 29

What is the result of compiling and executing the following code?
Which of the following should replace /* LINE */ to have the code compile and run with data: 225 sent to standard out?
A. n.data
B. n.data.data
C. n.data->data
D. n->data.data
E. None of the above.
Warning: You have not logged in. You cannot answer.

Question 30

Consider the following templated function definition:
Which of the following statements in the client main function will give a compiler error?
A. int b = printBIncrementA<int, std::string>(100, "my grade");
B. int b = printBIncrementA<int, int>(4, 8);
C. int b = printBIncrementA<int, double>(4, 4.1);
D. Exactly two of the above statements result in a compiler error.
E. All three of the above statements compile with no error.
Warning: You have not logged in. You cannot answer.

11. Linked memory, recursion, dictionaries, hash tables

Question 31

There is a bug in the following code:
Strings are being concatenated in reverse, resulting in !worldHello, output. Which solution would correctly output Hello, world!?
A. Change line 13 to return concatenate(args...);
B. Change line 13 to return std::string(first) + concatenate(args...)
C. Change line 13 to return concatenate(first, args...);
D. Change line 13 to return std::string(first) + concatenate(args...) + std::string(first);
E. Change line 13 to return std::string(first) + concatenate(args...) + std::string(args...);
Warning: You have not logged in. You cannot answer.

12. STL, iterators

Question 32

Which one of the following statements is FALSE?
A. Inserting elements at the end of a std::vector is more efficient than at the beginning.
B. Inserting and removing elements at the start of an std::list have constant time complexity.
C. A std::vector has elements arranged in memory contiguously.
D. Iterating over a std::map follows the order of keys, sorted by default.
E. Iterating through a std::vector is more memory-efficient than through a std::list.
F. Iterators provide a way to access elements in std containers sequentially without exposing the underlying container implementation.
G. The size of a std::array can be adjusted at runtime.
Warning: You have not logged in. You cannot answer.

13. Payroll Mock Code (25 points)

You have been provided with a codebase that defines an Employee class capable of handling employee details including their name, hourly rate, hours worked, and a unique emoticon representation based on their wage. The class structure and main function are already set up but lack several implementations which are outlined in the form of TODO comments. In the following five problems your task will be to implement the missing functionalities.
You can access the codebase here: https://godbolt.org/z/TfsbE6cK3.
You are welcome to modify the code in any way you like to answer the questions below. However, you may not modify any of the existing code; additions are only allowed in the specified sections to fulfill the TODO requirements. Upon successful compilation and execution of your modified code, the program should produce the following output on standard out:
Elmo: $675.00
Displaying emoji:
 . . .
. o o  .
.  __  .
 . . .
Zoe: $1900.00
Displaying emoji:
\|/ ____ \|/
 @~/ ,. \~@
/_( \__/ )_\
   \__U_/
Bubbles: $940.00
Displaying emoji:
 . . .
. o o  .
.  __  .
 . . .

Question 33

Which one of the following is the correct implementation of the function setName for the Employee class?
Warning: You have not logged in. You cannot answer.

Question 34

Which of the following is the proper implementation of the copy constructor for the Employee class that includes a nested Emoticon class?
Warning: You have not logged in. You cannot answer.

Question 35

Which of the following lines in main invokes a cctor of the Employee class?
A. Employee b = employees[0];
B. b.setName("Bubbles");
C. b.setHourlyRate(23.5);
D. b.setHoursWorked(40);
E. employees.push_back(b);
F. More than one above
G. None of the above
Warning: You have not logged in. You cannot answer.

Question 36

In the main function, implement a loop that iterates through the Employees vector, displaying each employee's details on std::cout.
Warning: You have not logged in. You cannot answer.

Question 37

Please submit the Godbolt link containing your completed code for exercises 35-38 in the textbox below. Ensure that the code compiles without warnings or errors, runs without memory issues, and produces the correct output.

Warning: You have not logged in. You cannot answer.

14. Course Feedback (Guaranteed Points)

Note: Make sure you go to the official Peppi feedback for IC00AQ92-3001 - C++ Programming to leave your comments there. This will greatly help the future development of this course.

Feedback 1

On a scale of 1 to 5, how much have you learned in the class? (1 is not much, 5 is a ton)
Warning: You have not logged in. You cannot answer.

Feedback 2

On a scale of 1 to 5, how was the pace of the course? (1 is too slow, 5 is too fast)
Warning: You have not logged in. You cannot answer.

Feedback 3

On a scale of 1 to 5, rate your general satisfaction with the course. (1 is profoundly dissatisfied, 5 is happy)
Remember, this is NOT the official course feedback. Please submit your official feedback through Peppi so we can continue improving the course!
Warning: You have not logged in. You cannot answer.
?
API stands for Application Programming Interface. In the context of this course, you can consider the header files to be such interfaces, as they determine what class functions and properties are public and thus accessible from anywhere.
AddressSanitizer (ASAN) is a memory error detector for C/C++. In this course, the makefiles will typically compile an executable that uses ASAN, with "-asan" at the end of its name.
The two notable access specifiers are:
  • public: class members defined after the public keyword are accessible from outside the class.
  • private: class members are generally private by default and thus not accessible from the outside
Constructor is a special non-static member function of a class that is used to initialize objects of its class type. A constructor is called upon initialization of an object. A constructor without arguments is a default constructor, but constructors that take arguments can be defined.
GDB, the GNU Project debugger, allows you to see what is going on `inside' another program while it executes -- or what another program was doing at the moment it crashed.
GDB can do four main kinds of things (plus other things in support of these) to help you catch bugs in the act:
  • Start your program, specifying anything that might affect its behavior.
  • Make your program stop on specified conditions.
  • Examine what has happened, when your program has stopped.
  • Change things in your program, so you can experiment with correcting the effects of one bug and go on to learn about another.
GNU Make is a tool which controls the generation of executables and other non-source files of a program from the program's source files. Make gets its knowledge of how to build your program from a file called the makefile, which lists each of the non-source files and how to compute it from other files. When you write a program, you should write a makefile for it, so that it is possible to use Make to build and install the program.
Memory leak means that the program is not freeing up memory it reserves. The memory will be freed when the program terminates, but if a program keeps leaking more and more memory without terminating, it can become a huge issue!
A typical way for memory leaks to occur is reserving memory with new and not calling delete before the pointer goes out of scope.
Pointer variables store a memory address as their value. In other words, they point to some data. The data can be accessed by dereferencing the pointer. (Either like *p or p->...)
A recursive function calls itself from within it. The recursion call must be conditional or it would lead to an infinite loop.
Valgrind is another tool besides ASAN that you can use in this course. It can detect many memory-related errors that are common in C and C++ programs and that can lead to crashes and unpredictable behaviour.
const is a keyword meant to mark something as immutable
  • A const object cannot be modified: attempt to do so directly is a compile-time error, and attempt to do so indirectly (e.g., by modifying the const object through a reference or pointer to non-const type) results in undefined behavior.
  • const keyword on an object's member function prevents the object from being modified in the function
  • Pointer declarations can have 2 const keywords, one to make the data that's pointed at unable to be modified and one to make the pointer itself unable to be modified
Using const improves code readability and prevents accidental modification of objects.
g++ is a C++ compiler that we primarily use for this course. It is the C++ compiler for the GNU compiler collection. You may sometimes see gcc being used instead of g++, which was originally the GNU C compiler, but calling gcc generally also compiles .cpp files as C++. However, calling g++ is preferred.
In C++, std stands for Standard Library, which is a collection of commonly useful classes and functions. Typically, these are defined in the std namespace.