Quiz 2 — Classes and Objects¶
Ten questions on defining types, access control, this, and member functions.
Attempt all of them closed-book, then mark yourself against
the answers.
Concepts: class definition · access specifiers · this · member functions ·
separating interface from implementation.
Q1. (MCQ) In a class, what is the default access for members?
- A.
public - B.
private - C.
protected - D. there is no default
Q2. (true/false) Two objects of the same class share the class's member functions but each has its own data members.
Q3. (multiple-select) Which of these make a good reason to make a member private?
Select all that apply.
- A. Keeping two fields consistent with each other
- B. Preventing a caller from setting an impossible value
- C. Hiding a helper the caller should not depend on
- D. Making the code shorter to type
Q4. (predict) Write the line this prints.
#include <iostream>
class Counter {
public:
Counter() : value_(0) {}
void increment() { ++value_; }
int value() const { return value_; }
private:
int value_;
};
int main() {
Counter a;
Counter b;
a.increment();
a.increment();
b.increment();
std::cout << a.value() << ' ' << b.value() << '\n';
}
Q5. (short answer) What does the this pointer refer to inside a member function?
Q6. (analysis) Why does a member function that only reads a data member need to be
declared const? Give one concrete situation where omitting it causes a compile error.
Q7. (MCQ) Which line is the class's interface rather than its implementation?
class Rectangle {
public:
double area() const { return width_ * height_; } // (1)
private:
double width_;
double height_;
};
- A. line (1), because it is public
- B. the
privatemembers - C. both, taken together
- D. neither
Q8. (debug) The accessor cannot be called on a const object. Fix it.
#include <iostream>
class Sensor {
public:
explicit Sensor(double celsius) : celsius_(celsius) {}
double celsius() { return celsius_; } // the problem
private:
double celsius_;
};
void report(const Sensor& s) {
std::cout << s.celsius() << '\n'; // error here
}
int main() {
Sensor s{21.5};
report(s);
}
Q9. (predict) Write what this prints.
#include <iostream>
class Box {
public:
Box() : open_(false) {}
void open() { open_ = true; }
void close() { open_ = false; }
bool isOpen() const { return open_; }
private:
bool open_;
};
int main() {
Box b;
std::cout << b.isOpen() << '\n';
b.open();
std::cout << b.isOpen() << '\n';
}
Q10. (design) A shopping-cart item needs a name, a unit price and a quantity. Give the class's public operations (signatures only) and one invariant you would enforce, and say which operation enforces it.
Scoring: mark yourself with the answers, then read the self-assessment guide.