C++ Structs & Basic Classes Quiz
Comprehensive C++ quiz exploring fundamental object-oriented programming concepts including struct vs class differences, member variables, methods, access specifiers, and object initialization patterns.
Question 1
When choosing between a struct and a class for a simple data container that needs to hold multiple related values, what is the most significant difference that affects default member accessibility?
#include <iostream>
struct Point {
int x, y; // Public by default
};
class Rectangle {
private: // Private by default
int width, height;
public:
void setSize(int w, int h) {
width = w; height = h;
}
};
int main() {
Point p = {10, 20}; // Direct access
std::cout << "Point: (" << p.x << "," << p.y << ")" << std::endl;
Rectangle r;
r.setSize(30, 40); // Must use methods
return 0;
}Question 2
What is the most important design principle that access specifiers (public, private) enforce in class design?
Question 3
When implementing a class that represents a bank account with balance and account number, what access specifier should be used for the balance member variable to maintain data integrity?
#include <iostream>
#include <string>
class BankAccount {
private:
double balance; // Private: controlled access
std::string accountNumber;
public:
BankAccount(std::string accNum, double initialBalance)
: accountNumber(accNum), balance(initialBalance) {}
void deposit(double amount) {
if(amount > 0) balance += amount;
}
bool withdraw(double amount) {
if(amount > 0 && balance >= amount) {
balance -= amount;
return true;
}
return false;
}
double getBalance() const {
return balance;
}
};
int main() {
BankAccount account("12345", 1000.0);
account.deposit(500);
std::cout << "Balance: $" << account.getBalance() << std::endl;
return 0;
}Question 4
What is the fundamental difference between member variables and local variables in terms of lifetime and accessibility within a class?
Question 5
When designing a class method that should not modify the object's state, what const qualifier should be applied to the method declaration?
#include <iostream>
class Circle {
private:
double radius;
public:
Circle(double r) : radius(r) {}
double getArea() const { // Const method
return 3.14159 * radius * radius;
// radius = 10; // ERROR: cannot modify in const method
}
void setRadius(double r) {
radius = r; // Non-const method can modify
}
};
int main() {
const Circle c(5.0); // Const object
std::cout << "Area: " << c.getArea() << std::endl;
// c.setRadius(10); // ERROR: cannot call non-const method
return 0;
}Question 6
What is the most significant advantage of using member functions over standalone functions for operations on class data?
Question 7
When implementing a struct to represent a 2D coordinate with x and y values, what initialization syntax provides the most convenient and readable object creation?
#include <iostream>
struct Coordinate {
double x, y;
// Constructor for flexible initialization
Coordinate(double x_val = 0, double y_val = 0)
: x(x_val), y(y_val) {}
};
int main() {
Coordinate c1; // Default: (0, 0)
Coordinate c2(3.5); // x=3.5, y=0
Coordinate c3(1.0, 2.0); // x=1.0, y=2.0
Coordinate c4 = {4.0, 5.0}; // Aggregate initialization
std::cout << "c4: (" << c4.x << ", " << c4.y << ")" << std::endl;
return 0;
}Question 8
What is the key principle that guides whether to make a class member public, private, or protected?
Question 9
When designing a class that represents a student with name, ID, and grades, what member access pattern provides the best balance of encapsulation and usability?
#include <iostream>
#include <string>
#include <vector>
class Student {
private:
std::string name;
int id;
std::vector<double> grades;
public:
Student(std::string n, int i) : name(n), id(i) {}
// Getters for read access
std::string getName() const { return name; }
int getId() const { return id; }
// Methods for controlled modifications
void addGrade(double grade) {
if(grade >= 0 && grade <= 100) {
grades.push_back(grade);
}
}
double getAverage() const {
if(grades.empty()) return 0.0;
double sum = 0;
for(double grade : grades) sum += grade;
return sum / grades.size();
}
};
int main() {
Student s("Alice", 12345);
s.addGrade(95.0);
s.addGrade(87.5);
std::cout << s.getName() << " (ID: " << s.getId() << ") Average: " << s.getAverage() << std::endl;
return 0;
}Question 10
What is the most important consideration when choosing between a struct and a class for a simple data transfer object that will be passed between functions?
Question 11
When implementing a class method that needs to access another object's private members, what language feature provides this capability?
#include <iostream>
class Point {
private:
int x, y;
// Friend function can access private members
friend void printDistance(const Point& p1, const Point& p2);
public:
Point(int x_val, int y_val) : x(x_val), y(y_val) {}
};
void printDistance(const Point& p1, const Point& p2) {
int dx = p1.x - p2.x; // Access private members
int dy = p1.y - p2.y;
std::cout << "Distance: " << (dx * dx + dy * dy) << std::endl;
}
int main() {
Point p1(0, 0), p2(3, 4);
printDistance(p1, p2);
return 0;
}Question 12
What is the fundamental purpose of member initialization in constructors, and why is it preferred over assignment in the constructor body?
Question 13
When designing a class hierarchy where derived classes need access to base class members but external code should not, what access specifier achieves this controlled inheritance?
#include <iostream>
class Vehicle {
protected: // Accessible to derived classes
int speed;
public:
Vehicle(int s) : speed(s) {}
void accelerate(int delta) { speed += delta; }
};
class Car : public Vehicle {
public:
Car(int s) : Vehicle(s) {}
void showSpeed() {
std::cout << "Speed: " << speed << std::endl; // Can access protected member
}
};
int main() {
Car c(60);
c.accelerate(20);
c.showSpeed();
// Vehicle v(50);
// std::cout << v.speed; // ERROR: protected member not accessible
return 0;
}Question 14
What is the most significant advantage of using methods over direct member access for data validation and business logic?
Question 15
When implementing a struct that represents a mathematical vector with multiple components, what combination of features provides the most natural and efficient usage?
#include <iostream>
struct Vector3D {
double x, y, z;
Vector3D(double x_val = 0, double y_val = 0, double z_val = 0)
: x(x_val), y(y_val), z(z_val) {}
Vector3D operator+(const Vector3D& other) const {
return Vector3D(x + other.x, y + other.y, z + other.z);
}
double length() const {
return std::sqrt(x*x + y*y + z*z);
}
};
int main() {
Vector3D v1(1, 2, 3);
Vector3D v2(4, 5, 6);
Vector3D sum = v1 + v2; // Natural syntax
std::cout << "Length: " << sum.length() << std::endl;
return 0;
}Question 16
What is the most important design consideration when deciding whether to implement functionality as a member function or a standalone function?
Question 17
When designing a class that represents a configuration object with many optional settings, what initialization approach provides the most readable and maintainable code?
#include <iostream>
#include <string>
class Config {
private:
std::string host = "localhost";
int port = 8080;
bool debug = false;
public:
// Default member initialization
Config() = default;
// Named parameter idiom using setters
Config& setHost(const std::string& h) { host = h; return *this; }
Config& setPort(int p) { port = p; return *this; }
Config& setDebug(bool d) { debug = d; return *this; }
void print() const {
std::cout << "Host: " << host << ", Port: " << port
<< ", Debug: " << (debug ? "on" : "off") << std::endl;
}
};
int main() {
Config cfg;
cfg.setHost("example.com").setPort(9000).setDebug(true);
cfg.print();
return 0;
}Question 18
What is the key difference between a struct and a class in terms of inheritance default access when no access specifier is provided?
Question 19
When implementing a class that manages a resource like a file handle, what access pattern ensures proper resource management while providing controlled external access?
#include <iostream>
#include <fstream>
#include <memory>
class FileHandler {
private:
std::unique_ptr<std::ofstream> file;
public:
FileHandler(const std::string& filename) {
file = std::make_unique<std::ofstream>(filename);
}
bool isOpen() const {
return file && file->is_open();
}
void writeLine(const std::string& line) {
if(file) {
*file << line << std::endl;
}
}
// No direct access to file pointer
};
int main() {
FileHandler handler("output.txt");
if(handler.isOpen()) {
handler.writeLine("Hello, World!");
}
// File automatically closed when handler is destroyed
return 0;
}Question 20
What is the most significant advantage of using const member functions for observer methods that don't modify state?
Question 21
When designing a struct to represent a database record with multiple fields, what combination of features provides the most efficient and convenient data access?
Question 22
What is the fundamental principle that guides the decision to make a member variable public, private, or provide accessor methods?
Question 23
When implementing a class that represents a geometric shape with area and perimeter calculations, what method design provides the most appropriate interface?
#include <iostream>
class Rectangle {
private:
double width, height;
public:
Rectangle(double w, double h) : width(w), height(h) {}
double getArea() const {
return width * height;
}
double getPerimeter() const {
return 2 * (width + height);
}
void scale(double factor) {
width *= factor;
height *= factor;
}
};
int main() {
Rectangle rect(10, 5);
std::cout << "Area: " << rect.getArea() << std::endl;
rect.scale(2);
std::cout << "Scaled area: " << rect.getArea() << std::endl;
return 0;
}Question 24
What is the most important consideration when choosing between member variables and computed properties (methods that return calculated values)?
Question 25
When designing a struct for a high-performance mathematical library, what access pattern provides the best performance while maintaining reasonable encapsulation?
Question 26
What is the key advantage of using default member initialization over constructor initialization for simple default values?
#include <iostream>
class Settings {
public:
int timeout = 30; // Default member initialization
bool enabled = true;
std::string name = "default";
Settings() = default; // Uses default member initializers
Settings(int t, bool e) : timeout(t), enabled(e) {
// name uses default member initializer
}
};
int main() {
Settings s1; // All defaults
Settings s2(60, false); // Partial override
std::cout << "s1: " << s1.name << ", " << s1.timeout << std::endl;
std::cout << "s2: " << s2.name << ", " << s2.timeout << std::endl;
return 0;
}Question 27
When implementing a class that represents a network connection with internal state management, what access control provides the best security and maintainability?
Question 28
What is the most significant benefit of using member functions for operations that require access to multiple private member variables?
Question 29
When designing a struct for interoperation with C libraries that expect plain data structures, what features should be minimized or avoided?
#include <iostream>
// C-compatible struct
struct C_Point {
double x, y; // Only public data, no methods
};
// C++ enhanced struct
struct Cpp_Point {
double x, y;
Cpp_Point(double x_val = 0, double y_val = 0)
: x(x_val), y(y_val) {}
double distance() const {
return std::sqrt(x*x + y*y);
}
};
extern "C" void c_function(C_Point* p); // C function
int main() {
Cpp_Point cpp_pt(3, 4);
std::cout << "Distance: " << cpp_pt.distance() << std::endl;
// Can pass to C function (struct layout compatible)
c_function(reinterpret_cast<C_Point*>(&cpp_pt));
return 0;
}Question 30
What is the most important principle to follow when designing public interfaces for classes that will be used by external code?
Question 31
When implementing a class that caches computed results, what member access pattern provides the best performance and encapsulation balance?
#include <iostream>
#include <unordered_map>
class ExpensiveCalculator {
private:
std::unordered_map<int, double> cache;
double computeExpensive(int input) {
// Simulate expensive computation
double result = 0;
for(int i = 0; i < input; ++i) {
result += std::sin(i) * std::cos(i);
}
return result;
}
public:
double calculate(int input) {
auto it = cache.find(input);
if(it != cache.end()) {
return it->second;
}
double result = computeExpensive(input);
cache[input] = result;
return result;
}
void clearCache() {
cache.clear();
}
};
int main() {
ExpensiveCalculator calc;
std::cout << "Result: " << calc.calculate(1000) << std::endl;
std::cout << "Cached result: " << calc.calculate(1000) << std::endl;
return 0;
}Question 32
What is the fundamental advantage of using structs over classes for representing mathematical vectors in high-performance computing?
Question 33
When designing a class hierarchy where base classes define interfaces that derived classes implement, what access specifier should be used for interface methods?
#include <iostream>
class Shape {
public:
virtual double area() const = 0; // Pure virtual interface
virtual ~Shape() = default;
};
class Circle : public Shape {
private:
double radius;
public:
Circle(double r) : radius(r) {}
double area() const override {
return 3.14159 * radius * radius;
}
};
int main() {
Shape* shape = new Circle(5);
std::cout << "Area: " << shape->area() << std::endl;
delete shape;
return 0;
}Question 34
What is the most significant trade-off when choosing public data members in structs versus private members with accessors in classes?
Question 35
When implementing a struct that needs to be serialized to binary format for network transmission, what design considerations are most important?
#include <iostream>
#include <cstring>
#pragma pack(push, 1) // Disable padding
struct NetworkPacket {
uint32_t sequence;
uint16_t length;
char data[100];
// No virtual functions, no private members
// Standard layout for safe binary operations
};
#pragma pack(pop)
int main() {
NetworkPacket packet = {12345, 10};
strcpy(packet.data, "Hello");
// Can safely memcpy or send over network
std::cout << "Packet size: " << sizeof(NetworkPacket) << std::endl;
return 0;
}Question 36
What is the most important principle to consider when deciding whether to add a method to a class versus keeping it as a standalone utility function?
Question 37
When designing a class that represents a thread-safe counter, what member access pattern ensures proper synchronization while maintaining usability?
#include <iostream>
#include <mutex>
class ThreadSafeCounter {
private:
int value = 0;
std::mutex mutex;
public:
void increment() {
std::lock_guard<std::mutex> lock(mutex);
++value;
}
int getValue() const {
std::lock_guard<std::mutex> lock(mutex);
return value;
}
};
int main() {
ThreadSafeCounter counter;
counter.increment();
std::cout << "Value: " << counter.getValue() << std::endl;
return 0;
}Question 38
What is the key advantage of using default arguments in constructors over multiple overloaded constructors?
#include <iostream>
class Window {
private:
int width, height;
std::string title;
public:
// Single constructor with defaults
Window(int w = 800, int h = 600, std::string t = "Window")
: width(w), height(h), title(t) {}
void print() const {
std::cout << title << ": " << width << "x" << height << std::endl;
}
};
int main() {
Window w1; // All defaults
Window w2(1024); // Width override
Window w3(1024, 768); // Width and height
Window w4(1024, 768, "Game"); // All parameters
w1.print(); w2.print(); w3.print(); w4.print();
return 0;
}Question 39
When implementing a struct for a graphics vertex with position, normal, and texture coordinates, what combination provides the most efficient rendering pipeline compatibility?
Question 40
What is the most critical design consideration when choosing between struct and class keywords for a new type definition?
