WS2023/2024: Exam 2024-02-02 (Sample)

Name

Question 1

Given the following (incomplete) class definition ..

class point
{
public:
    int x() const { return _x; }
};

Question 1.1

Would the following code snippet compile?

const point p(1,2);
cout << p.x() << endl;

Yes

No

Question 1.2

Would the following code snippet compile?

point p(1,2);
cout << p.x() << endl;

Yes

No

Question 2

Question 2.1

Which of the following (partial) class definition would lead to better performance in object initialization

Variant A
class Person
{
public:
    Person(std::string firstname, std::string lastname);
};
Variant B
class Person
{
public:
    Person(const std::string& firstname, const std::string& lastname);
};

Variant A

Variant B

Question 2.2 (Why?)

Why does the chosen variant perform better? (Write an X in the “True” or “False” columns)

True

False

Statement

Variant A has a shorter calling sequence

Variant A is better at moving the parameters into the object

Variant B does not create temporary copies

Question 3

Consider the following Sensor hierarchy (and imagine that there are many more implementations like W1Sensor out there that implement the Sensor interface).

#pragma once

class Sensor
{
public:
    virtual ~Sensor() {}
    virtual double get_temperature() = 0;

    Sensor(unsigned int id) : _id(id) {}

    // unused, mostly
    unsigned int id() const { return _id; }

private:
    // unused, mostly
    unsigned int _id;
};
#pragma once

#include "sensor.h"
#include <cstdint>


class W1Sensor : public Sensor
{
public:
    W1Sensor(unsigned int id, uint64_t w1_address)
    : Sensor(id),
      _w1_address(w1_address) {}

    double get_temperature() override
    {
        // ... access physical sensor ...
        return 36.5;
    }

private:
    uint64_t _w1_address;
};

Here is a sampe usage of the W1Sensor class.

#include "sensor-w1.h"
#include <unistd.h>
#include <iostream>

int main()
{
    W1Sensor sensor(/*id*/ 666, // unused in this program
                    /*w1_address*/ 0xdeadbeefUL);

    while (true) {
        double temperature = sensor.get_temperature();
        std::cout << temperature << std::endl;

        sleep(1);
    }

    return 0;
}

Which of the five SOLID principles are violated? (Wrong answers are subtracted from correct answers)

X if violated

Principle

Single Responsibility

Open/Closed

Liskov Substitution

Interface Segregation

Dependency Inversion