C++ Structs & Basic Classes Quiz

C++
0 Passed
0% acceptance

Comprehensive C++ quiz exploring fundamental object-oriented programming concepts including struct vs class differences, member variables, methods, access specifiers, and object initialization patterns.

40 Questions
~80 minutes
1

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?

cpp
#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;
}
A
Structs have public default access while classes have private default access, making structs suitable for simple data containers and classes for encapsulated objects with controlled access
B
Structs and classes have identical default access levels
C
Classes have public default access while structs have private access
D
Default access levels are irrelevant for choosing between structs and classes
2

Question 2

What is the most important design principle that access specifiers (public, private) enforce in class design?

A
Access specifiers enforce encapsulation by controlling what parts of a class are visible to external code, preventing direct manipulation of internal state and enabling controlled interfaces
B
Access specifiers have no effect on class design
C
Access specifiers only affect performance
D
All class members should always be public
3

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?

cpp
#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;
}
A
Private access for balance ensures data integrity by forcing all modifications through controlled methods that can validate operations and maintain invariants
B
Public access allows direct manipulation for better performance
C
Protected access is most appropriate for bank account data
D
Access specifiers have no impact on data integrity
4

Question 4

What is the fundamental difference between member variables and local variables in terms of lifetime and accessibility within a class?

A
Member variables exist for the lifetime of the object and are accessible throughout all member functions, while local variables exist only during function execution and are not accessible outside their scope
B
Member and local variables have identical lifetime and accessibility
C
Local variables last longer than member variables
D
Member variables are only accessible from outside the class
5

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?

cpp
#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;
}
A
Const qualifier on methods prevents state modification and allows calling on const objects, enabling read-only operations while maintaining const correctness
B
Const methods are slower than non-const methods
C
All methods should be const by default
D
Const qualifier has no effect on method behavior
6

Question 6

What is the most significant advantage of using member functions over standalone functions for operations on class data?

A
Member functions have implicit access to private members and the this pointer, enabling encapsulation while providing natural syntax for object operations
B
Member functions are slower than standalone functions
C
Standalone functions provide better encapsulation
D
Member functions cannot access private data
7

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?

cpp
#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;
}
A
Constructor with default parameters combined with aggregate initialization provides flexible object creation with clear syntax for different initialization scenarios
B
Only aggregate initialization should be used for structs
C
Constructors make structs less convenient to use
D
Structs cannot have constructors
8

Question 8

What is the key principle that guides whether to make a class member public, private, or protected?

A
Access levels should be based on the principle of least privilege, exposing only what external code needs while hiding implementation details to maintain flexibility
B
All members should be public for maximum accessibility
C
Access specifiers have no impact on design principles
D
Private members make classes unusable
9

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?

cpp
#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;
}
A
Private data with public getter methods and controlled modifier methods provides encapsulation while enabling safe external access and validation of changes
B
All data should be public for direct access
C
Getters and setters reduce encapsulation
D
Private members make classes too restrictive
10

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?

A
Structs are preferred for plain data objects due to public default access and aggregate initialization, while classes are better when encapsulation and methods are needed
B
Classes are always preferred over structs
C
Structs and classes have identical semantics
D
Data transfer objects should never use structs
11

Question 11

When implementing a class method that needs to access another object's private members, what language feature provides this capability?

cpp
#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;
}
A
Friend declarations grant specific functions or classes access to private members, enabling controlled violations of encapsulation when necessary for related functionality
B
All functions can access private members by default
C
Friend declarations are not allowed in C++
D
Private members are never accessible from outside the class
12

Question 12

What is the fundamental purpose of member initialization in constructors, and why is it preferred over assignment in the constructor body?

A
Member initialization directly constructs members with provided values, avoiding default construction followed by assignment, which is more efficient and required for const/reference members
B
Assignment in constructor body is always more efficient
C
Member initialization has no performance benefits
D
Constructor initialization is optional
13

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?

cpp
#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;
}
A
Protected access allows derived classes to access members while preventing external access, enabling inheritance hierarchies with controlled member visibility
B
Protected members are accessible from anywhere
C
Private access is better for inheritance
D
Protected access has no practical use
14

Question 14

What is the most significant advantage of using methods over direct member access for data validation and business logic?

A
Methods can implement validation logic and maintain invariants, ensuring data integrity and providing a single point for implementing business rules and constraints
B
Direct member access is always more efficient
C
Methods make data validation impossible
D
Business logic belongs in global functions
15

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?

cpp
#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;
}
A
Public data members with constructor and methods provides direct access for performance while offering convenience methods for complex operations and operator overloading
B
All data should be private in structs
C
Structs should never have methods
D
Operator overloading makes structs less efficient
16

Question 16

What is the most important design consideration when deciding whether to implement functionality as a member function or a standalone function?

A
Member functions should be used when the operation is fundamentally tied to the object's state or needs access to private members, while standalone functions work with public interfaces
B
All functions should be member functions
C
All functions should be standalone functions
D
Function placement has no impact on design
17

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?

cpp
#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;
}
A
Default member initialization combined with fluent setter methods provides clear, readable configuration while maintaining encapsulation and allowing method chaining
B
Constructor with many parameters is always more readable
C
Configuration objects should have all public members
D
Default initialization makes classes less maintainable
18

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?

A
Struct inheritance defaults to public while class inheritance defaults to private, affecting how base class members are accessible in derived classes
B
Structs and classes have identical inheritance defaults
C
Class inheritance defaults to public access
D
Inheritance access specifiers are always required
19

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?

cpp
#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;
}
A
Private resource management with public methods for controlled operations ensures proper resource lifecycle while preventing external misuse and ensuring automatic cleanup
B
Resource handles should always be public for direct access
C
Private resources make classes unusable
D
Resource management belongs in global functions
20

Question 20

What is the most significant advantage of using const member functions for observer methods that don't modify state?

A
Const member functions can be called on const objects and clearly express intent that no state changes occur, enabling broader usage and preventing accidental modifications
B
Const functions are slower than non-const functions
C
All member functions should be const
D
Const qualification has no practical benefits
21

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?

A
Public data members with aggregate initialization and convenience methods provides direct access performance while offering computed properties and validation when needed
B
All struct members must be private
C
Database records should use classes instead of structs
D
Public data makes structs less efficient
22

Question 22

What is the fundamental principle that guides the decision to make a member variable public, private, or provide accessor methods?

A
Implementation hiding principle suggests making variables private and providing accessors, allowing internal representation changes without breaking external code
B
All variables should be public for maximum performance
C
Accessor methods reduce performance without benefits
D
Implementation details are irrelevant to API design
23

Question 23

When implementing a class that represents a geometric shape with area and perimeter calculations, what method design provides the most appropriate interface?

cpp
#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;
}
A
Const getter methods for queries and non-const methods for modifications provides clear separation between read and write operations with appropriate const correctness
B
All methods should modify object state
C
Const methods prevent proper functionality
D
Method design has no impact on class usability
24

Question 24

What is the most important consideration when choosing between member variables and computed properties (methods that return calculated values)?

A
Computed properties should be used when values depend on other state or require calculation, while member variables work for independent stored values that need fast access
B
All values should be stored as member variables
C
Computed properties are always slower than member variables
D
Member variables and computed properties are interchangeable
25

Question 25

When designing a struct for a high-performance mathematical library, what access pattern provides the best performance while maintaining reasonable encapsulation?

A
Public data members enable direct access and compiler optimizations like auto-vectorization, while documentation guides proper usage for performance-critical code
B
High-performance code should never use structs
C
Private members with inline accessors provide the best performance
D
Encapsulation always takes precedence over performance
26

Question 26

What is the key advantage of using default member initialization over constructor initialization for simple default values?

cpp
#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;
}
A
Default member initialization provides clear default values at declaration while allowing constructors to override only specific values, reducing constructor complexity
B
Default member initialization is less efficient than constructor initialization
C
All initialization must occur in constructors
D
Default member initialization makes code less readable
27

Question 27

When implementing a class that represents a network connection with internal state management, what access control provides the best security and maintainability?

A
Private implementation with public interface methods ensures internal state protection while providing controlled access to connection operations and status queries
B
Network connections should have all members public for direct access
C
Private members make network classes unusable
D
Access control is irrelevant for network programming
28

Question 28

What is the most significant benefit of using member functions for operations that require access to multiple private member variables?

A
Member functions can coordinate access to multiple private members while maintaining encapsulation, enabling complex operations that would be impossible with external functions
B
Member functions cannot access multiple private members
C
External functions are better for multi-member operations
D
Private members should never be accessed together
29

Question 29

When designing a struct for interoperation with C libraries that expect plain data structures, what features should be minimized or avoided?

cpp
#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;
}
A
Virtual functions, private members, and complex inheritance should be avoided to maintain standard layout compatibility with C structures and enable seamless interoperation
B
C++ features should always be used in structs for C interoperation
C
C interoperation requires special compiler flags
D
Structs cannot interoperate with C code
30

Question 30

What is the most important principle to follow when designing public interfaces for classes that will be used by external code?

A
Public interfaces should follow the principle of least surprise, providing intuitive operations with clear contracts while hiding implementation details to enable future changes
B
Public interfaces should expose all internal implementation details
C
Interface design has no impact on usability
D
All class interfaces should be identical
31

Question 31

When implementing a class that caches computed results, what member access pattern provides the best performance and encapsulation balance?

cpp
#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;
}
A
Private cache with public calculation methods provides encapsulation of caching logic while offering controlled access to computation results and cache management
B
Cache should be public for direct access and modification
C
Caching logic belongs in global functions
D
Private caches make classes less efficient
32

Question 32

What is the fundamental advantage of using structs over classes for representing mathematical vectors in high-performance computing?

A
Public data members enable compiler optimizations like auto-vectorization and efficient memory access patterns that would be blocked by accessor methods in classes
B
Structs are always slower than classes for mathematical operations
C
High-performance computing should avoid structs
D
Public members prevent proper encapsulation in HPC
33

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?

cpp
#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;
}
A
Public virtual methods define the interface that derived classes must implement, enabling polymorphic behavior while maintaining consistent external access
B
Interface methods should be private to hide implementation
C
Protected methods are better for interfaces
D
Interface design doesn't require specific access specifiers
34

Question 34

What is the most significant trade-off when choosing public data members in structs versus private members with accessors in classes?

A
Public data provides better performance and simplicity but sacrifices encapsulation and future evolution, while private data with accessors enables controlled changes at the cost of syntactic overhead
B
Public data is always better than private data
C
Private data provides no benefits over public data
D
Access patterns have no impact on performance
35

Question 35

When implementing a struct that needs to be serialized to binary format for network transmission, what design considerations are most important?

cpp
#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;
}
A
Standard layout with no virtual functions or private members ensures predictable memory layout and safe binary serialization without padding or vtable complications
B
Network serialization requires complex conversion functions
C
Virtual functions improve network serialization
D
Private members are required for network data
36

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?

A
Methods should be added when they operate primarily on the object's state or provide object-specific behavior, while utility functions work when operations are generally applicable
B
All operations should be member methods
C
All operations should be standalone functions
D
Method placement has no design implications
37

Question 37

When designing a class that represents a thread-safe counter, what member access pattern ensures proper synchronization while maintaining usability?

cpp
#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;
}
A
Private data with synchronized public methods ensures thread safety by controlling all access points while providing intuitive operations for external code
B
Thread-safe classes should have public data for direct access
C
Synchronization belongs in external functions
D
Private members prevent thread safety
38

Question 38

What is the key advantage of using default arguments in constructors over multiple overloaded constructors?

cpp
#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;
}
A
Default arguments reduce code duplication and provide flexible initialization with a single constructor implementation, avoiding the complexity of multiple overloads
B
Multiple constructors are always more maintainable
C
Default arguments make constructors less readable
D
Constructor overloading is more efficient
39

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?

A
Contiguous public data members in standard layout enable direct GPU memory transfer and efficient vertex buffer operations without accessor overhead
B
Graphics structs should use private members with accessors
C
Virtual methods improve graphics performance
D
Standard layout is irrelevant for graphics programming
40

Question 40

What is the most critical design consideration when choosing between struct and class keywords for a new type definition?

A
Struct should be used for plain data aggregates with public interface, while class indicates encapsulated types with private implementation and complex behavior
B
The keywords are completely interchangeable
C
Class should always be preferred over struct
D
Struct should always be preferred over class

QUIZZES IN C++