📝 Comprehensive CSE 2100 Lab Quiz Practice Bank

Overview

This Comprehensive CSE 2100 Lab Quiz Practice Bank has been compiled directly from laboratory exam sheets and the refined curriculum of Lessons 1 to 8.

It covers: Fill in the Gaps, True/False, Multiple Choice (MCQs), and “Find the Error” debug drills, followed by an Unabridged Answer Key with Explanations at the bottom.


🏷️ Topic 1: Transitioning from C to C++ and Core Class Structure

(Refer to: lesson-1-intro-to-oop-and-classes)

✏️ Section A: Fill in the Gaps

  1. OOP follows a ____________ design approach, unlike procedural C which is top-down.
  2. By default, all members of a C++ class are ____________.
  3. The ____________ standard stream in C++ represents the unbuffered error stream.
  4. In C++, a struct is virtually identical to a class, except its members default to ____________.

✗ Section B: True / False

  1. True or False: Memory for a class’s member functions is allocated separately inside every instantiated object to ensure isolation.
  2. True or False: In C++, the extraction operator (>>) can read an entire line of text including spaces into a std::string.

💎 Section C: Multiple Choice Questions (MCQs)

  1. Which OOP concept focuses on wrapping up data and functions into a single cohesive unit?
    • A. Abstraction
    • B. Inheritance
    • C. Encapsulation
    • D. Polymorphism
  2. What error will the statement cin << age; trigger during compilation?
    • A. Variable undefined error
    • B. Invalid operands to binary expression (Operator Reversal)
    • C. Type conversion failure
    • D. Missing semicolon error

🔍 Section D: Find the Error in Code

  1. Identify the compile-time syntax error in this class declaration:
    class Item {
        int itemCode;
        float price;
    }
     
    int main() {
        Item obj;
        return 0;
    }

🏷️ Topic 2: Member Functions & Arrays of Objects

(Refer to: lesson-2-member-functions-and-arrays)

✏️ Section A: Fill in the Gaps

  1. The ____________ operator is used to define member functions outside the class declaration.
  2. Functions defined directly inside a class body are implicitly treated as ____________ by the compiler.
  3. Calling a member function from inside another member function of the same class without using the dot operator is called ____________.

✗ Section B: True / False

  1. True or False: If an object is passed to a function by value, any modifications made to its fields inside the function will persist in main() after execution completes.
  2. True or False: The compiler is forced to inline any function that is prefixed with the inline keyword, regardless of loops or size.

💎 Section C: Multiple Choice Questions (MCQs)

  1. To pass an object to a function with maximum efficiency (avoiding copying overhead) while guaranteeing read-only safety, you should pass it as:
    • A. void print(Item obj)
    • B. void print(Item &obj)
    • C. void print(const Item &obj)
    • D. void print(Item *obj)

🔍 Section D: Find the Error in Code

  1. Find the mistake in this outside member function implementation:
    class Distance {
    private:
        int feet;
    public:
        void setFeet(int f);
    };
     
    void setFeet(int f) {
        feet = f;
    }

🏷️ Topic 3: The Lifecycle of an Object (Constructors & Destructors)

(Refer to: lesson-3-object-lifecycle)

✏️ Section A: Fill in the Gaps

  1. A destructor has the same name as its class but is preceded by the ____________ symbol.
  2. A constructor that accepts a reference to its own class as a parameter is called a ____________ constructor.
  3. To dynamically allocate memory on the heap, C++ uses the ____________ operator.
  4. The ____________ is a high-performance syntax used in constructors to initialize class member variables before the body block executes.

✗ Section B: True / False

  1. True or False: Destructors can be overloaded based on parameter count, allowing classes to have multiple cleanup routines.
  2. True or False: If a class contains a pointer to a heap-allocated array, using the compiler’s default Copy Constructor results in a deep copy.

💎 Section C: Multiple Choice Questions (MCQs)

  1. What is the return type of a destructor?
    • A. void
    • B. int
    • C. Same as the class name
    • D. No return type (not even void)
  2. Why must a copy constructor’s parameter be passed by reference rather than by value?
    • A. To prevent the compiler from making the constructor virtual.
    • B. To bypass private access rules.
    • C. Passing by value triggers infinite copy-constructor recursion.
    • D. To force the compiler to store the object in the global data segment.

🔍 Section D: Find the Error in Code

  1. Identify the critical bug in this string management class that violates the “Rule of Three” memory safety guidelines:
    class MyString {
    private:
        char* buffer;
        int size;
    public:
        MyString(const char* src) {
            size = strlen(src);
            buffer = new char[size + 1];
            strcpy(buffer, src);
        }
        ~MyString() {
            delete[] buffer;
        }
        MyString(const MyString& other) {
            size = other.size;
            buffer = new char[size + 1];
            strcpy(buffer, other.buffer);
        }
    };
     
    int main() {
        MyString s1("Hello");
        MyString s2("World");
        s2 = s1; // CRITICAL TRAP HERE
        return 0;
    }

🏷️ Topic 4: Foundations of Inheritance & Visibility Modes

(Refer to: lesson-4-inheritance-basics)

✏️ Section A: Fill in the Gaps

  1. Visibility modes default to ____________ if no keyword is provided during class derivation.
  2. When a derived class object is created, constructors execute from ____________ class to ____________ class.
  3. When a derived class object goes out of scope, destructors are invoked in the ____________ order of constructors.

✗ Section B: True / False

  1. True or False: Private members of a base class are directly inherited and accessible inside the derived class’s member functions.
  2. True or False: Base class constructors and destructors are never inherited by derived classes.

💎 Section C: Multiple Choice Questions (MCQs)

  1. In private inheritance, public members of the base class become what in the derived class?
    • A. Public
    • B. Protected
    • C. Private
    • D. Inaccessible
  2. Which access specifier allows member variables to be accessed directly inside derived classes, but shields them from direct external access in main()?
    • A. Public
    • B. Protected
    • C. Private
    • D. Friend

🔍 Section D: Find the Error in Code

  1. Explain why the following derived class will fail to compile:
    class Parent {
    public:
        Parent(int x) { cout << "Parent constructed with " << x; }
    };
     
    class Child : public Parent {
    public:
        Child() { cout << "Child constructed"; }
    };

🏷️ Topic 5: Advanced Inheritance, Diamond Problem & Friends

(Refer to: lesson-5-advanced-inheritance)

✏️ Section A: Fill in the Gaps

  1. The diamond problem occurs when a derived class inherits from two parent classes that share a common grandparent class via ____________ inheritance.
  2. To resolve variable duplication in the diamond problem, intermediate classes must inherit the grandparent class as ____________.
  3. Memory for static member variables is allocated in the global ____________ segment instead of inside individual objects.
  4. A friend function is defined outside the class ____________ the friend keyword and ____________ class scope resolution prefix.

✗ Section B: True / False

  1. True or False: Static member functions can directly read and write both static and non-static member variables of a class.
  2. True or False: A static variable must be declared inside the class block but defined and initialized globally outside the class.

💎 Section C: Multiple Choice Questions (MCQs)

  1. Which of the following statements about friend functions is FALSE?
    • A. A friend function has direct access to a class’s private and protected sections.
    • B. A friend function is not a member function of the class.
    • C. A friend function has an implicit this pointer pointing to the invoking object.
    • D. A friend function can be declared in either the private or public section.

🔍 Section D: Find the Error in Code

  1. Identify the design bug in this global friend declaration:
    class Box {
    private:
        int width;
    public:
        Box(int w) : width(w) {}
        int getWidth(Box b);
    };
     
    int getWidth(Box b) {
        return b.width;
    }

🏷️ Topic 6: The this Pointer & Operator Overloading

(Refer to: lesson-6-this-and-operators)

✏️ Section A: Fill in the Gaps

  1. Within any non-static member function, the ____________ pointer holds the exact memory address of the invoking object.
  2. To allow method cascading (such as calc.add(5).sub(2)), a member function must return ____________.
  3. The operators ::, ., .*, and ?: cannot be overloaded in C++. Another non-overloadable operator is ____________.

✗ Section B: True / False

  1. True or False: You can invent new operator symbols, such as @ or **, by overloading them inside C++ class definitions.
  2. True or False: Overloading can change the default precedence and associativity rules of existing operators.

💎 Section C: Multiple Choice Questions (MCQs)

  1. To differentiate prefix increment (++p) from postfix increment (p++) during overloading, the postfix operator signature must include a dummy:
    • A. double parameter
    • B. int parameter
    • C. const qualifier
    • D. Class pointer
  2. Stream operators << and >> are typically overloaded as friend/non-member functions instead of class member functions because:
    • A. Friend functions have a smaller memory footprint.
    • B. The left-hand operand is a stream object (like std::ostream), not our class object.
    • C. Member functions cannot handle binary operations.
    • D. Friend functions are faster at runtime.

🔍 Section D: Find the Error in Code

  1. Identify the compilation error in this binary addition overload:
    class Complex {
    private:
        float real, imag;
    public:
        Complex(float r, float i) : real(r), imag(i) {}
     
        // Member overload for binary addition
        Complex operator+(Complex c1, Complex c2) {
            return Complex(c1.real + c2.real, c1.imag + c2.imag);
        }
    };

🏷️ Topic 7: Dynamic Binding & Polymorphism

(Refer to: lesson-7-polymorphism)

✏️ Section A: Fill in the Gaps

  1. Compile-time polymorphism uses ____________ binding, whereas runtime polymorphism uses ____________ binding.
  2. A virtual function is declared in the parent class using the keyword ____________.
  3. A base class containing at least one ____________ virtual function is called an Abstract Class.
  4. The compiler handles runtime virtual function dispatch using a static lookup table called a ____________ and an instance pointer called ____________.

✗ Section B: True / False

  1. True or False: Just like member functions, constructors in C++ can be declared virtual to allow dynamic object initialization.
  2. True or False: If a class has at least one virtual function, its destructor should also be declared virtual.

💎 Section C: Multiple Choice Questions (MCQs)

  1. What happens if you delete a derived-class object through a base-class pointer when the base class destructor is NOT virtual?
    • A. The derived class destructor is called, but the base destructor is bypassed.
    • B. Only the base class destructor is executed, leading to potential heap memory leaks in the derived subobject.
    • C. A compilation error occurs.
    • D. The compiler automatically corrects the binding at runtime.

🔍 Section D: Find the Error in Code

  1. Find the runtime bug in this dynamic allocation setup:
    class Animal {
    public:
        void speak() { cout << "Animal noise"; }
    };
     
    class Cat : public Animal {
    public:
        void speak() { cout << "Meow"; }
    };
     
    int main() {
        Animal* ptr = new Cat();
        ptr->speak(); // Expected: "Meow"
        delete ptr;
        return 0;
    }

🏷️ Topic 8: File Streams & Output Formatting

(Refer to: lesson-8-file-handling-and-formatting)

✏️ Section A: Fill in the Gaps

  1. The file stream query function ____________ returns the current absolute byte offset of the file read-pointer.
  2. Parameterized stream manipulators (like setw and setfill) require including the ____________ header file.
  3. Opening an fstream object for simultaneously reading and writing is achieved using the bitwise OR syntax ____________.
  4. To seek backward by 15 bytes relative to the current pointer position in a file, you write: file.seekg(______, ios::cur).

✗ Section B: True / False

  1. True or False: The width manipulator setw(int width) is persistent and remains active for all subsequent stream outputs until changed.
  2. True or False: Performing relative byte seeking with a negative offset (e.g. seekg(-10, ios::cur)) is safely portable on standard text-mode streams.

💎 Section C: Multiple Choice Questions (MCQs)

  1. What is the exact console output of the following statement? cout << setw(8) << setfill('&') << 90 << 1 << endl;
    • A. &&&&&&90&&&&&&1
    • B. &&&&&&901
    • C. &&&&&&&&901
    • D. 90&&&&&&1
  2. Which ios base stream state flag represents a non-fatal formatting mismatch during an input operation?
    • A. ios::goodbit
    • B. ios::badbit
    • C. ios::failbit
    • D. ios::eofbit

🔍 Section D: Find the Error in Code

  1. Spot the formatting compilation trap in this source file:
    #include <iostream>
    using namespace std;
     
    int main() {
        float pi = 22.0/7.0;
        cout.fill("$");
        cout.width(10);
        cout << pi << endl;
        return 0;
    }

🔑 Complete Answer Key & Explanations

Topic 1 Answers

  1. Bottom-up (OOP begins with objects and builds systems upwards, while POP decomposes tasks top-down).
  2. Private (By default, class members block outside access to secure data).
  3. std::cerr (Standard unbuffered error stream, displaying logs instantly).
  4. Public (Only distinction between C++ struct and class).
  5. FALSE (Functions are allocated once in read-only code space; objects only allocate data properties).
  6. FALSE (The extraction operator >> stops at whitespace. To read spaces, use getline(cin, str)).
  7. C. Encapsulation (Bundling attributes and methods into one capsule).
  8. B. Invalid operands to binary expression (Reversing << and >> on streams throws a compiler error).
  9. Missing Semicolon: Class declarations must end with a semicolon ; following the closing brace. Fix: };

Topic 2 Answers

  1. Scope resolution (::) (Tells the compiler which class scope a member belongs to).
  2. Inline (Compiler replaces call sites directly to optimize pipeline).
  3. Nesting (Calling class functions internally without object wrappers).
  4. FALSE (Pass-by-value replicates the object on the stack; main’s original object remains untouched).
  5. FALSE (The inline keyword is a suggestion; compilers ignore it for complex loops or recursive routines).
  6. C. void print(const Item &obj) (Const reference prevents copying overhead while securing raw data).
  7. Missing Scope Resolution Prefix: Defining member functions outside the class requires class membership labels. Fix: void Distance::setFeet(int f) { ... }.

Topic 3 Answers

  1. Tilde (~) (The prefix that denotes destructor cleanup).
  2. Copy (Initializes an object using an identical sibling instance).
  3. new (C++ dynamic heap allocation operator).
  4. Constructor Initializer List (Direct member assignment syntax, skipping default constructor overhead).
  5. FALSE (Destructors take zero parameters; therefore, overloading signatures is impossible).
  6. FALSE (Default copy constructors perform shallow copies, leading to multiple objects pointing to the same heap address).
  7. D. No return type (Destructors have no return value—not even void).
  8. C. Passing by value triggers infinite copy-constructor recursion (Value passing requires copying, which invokes the copy constructor… forever).
  9. Rule of Three Violation: The code implements a custom Copy Constructor and Destructor but misses the Copy Assignment Operator (operator=). Simple assignments like s2 = s1 will trigger a shallow member copy, leading to a double-free runtime crash.
    • Fix: Add:
      MyString& operator=(const MyString& other) {
          if (this != &other) {
              delete[] buffer;
              size = other.size;
              buffer = new char[size + 1];
              strcpy(buffer, other.buffer);
          }
          return *this;
      }

Topic 4 Answers

  1. private (C++ class inheritance defaults to private; structs default to public).
  2. Base to Derived (Parent constructor runs first to build baseline attributes).
  3. Reverse (Destruction layers peel off backward: derived first, base last).
  4. FALSE (Private base members are inherited but completely inaccessible inside derived classes).
  5. TRUE (Constructors and destructors are not inherited; each class defines its own setup and teardown footprint).
  6. C. Private (Private inheritance changes base public and protected elements to private).
  7. B. Protected (Protected variables are inherited directly but block external main accesses).
  8. Missing Default Base Constructor: Parent has a parameterized constructor, removing the automatic compiler-generated default constructor. Child’s default constructor will fail because it cannot implicitly call a default constructor in Parent.
    • Fix: Pass parameters upward: Child() : Parent(0) { ... }.

Topic 5 Answers

  1. Multiple (or Hybrid) (Multiple base pathways converge, duplicating grandparent records).
  2. virtual (Virtual inheritance establishes a single shared grandparent subobject).
  3. Static/Global (Static members live in a dedicated segment, shared by all instances).
  4. Without, without (Friend functions are global helpers; they do not have class scope).
  5. FALSE (Static member functions lack a this pointer and can only access static class members).
  6. TRUE (Declaring inside doesn’t allocate memory; definition globally outside is mandatory).
  7. C. A friend function has an implicit this pointer (Since they are not members, friends cannot access this).
  8. Missing Friend Keyword: Box::getWidth lacks the friend prefix inside the class block.
    • Fix: Change declaration inside Box to: friend int getWidth(Box b);.

Topic 6 Answers

  1. this (Implicit pointer holding the current object address).
  2. *this by reference (ClassName&) (Enables sequential chaining of methods on the same memory block).
  3. sizeof (Or .*, as they resolve static types or names instead of operating on dynamic values).
  4. FALSE (You can only overload existing C++ operator symbols).
  5. FALSE (Precedence and associativity rules cannot be altered).
  6. B. int parameter (A dummy int parameter distinguishes post-increment from pre-increment).
  7. B. The left-hand operand is a stream object (Streams like cout cannot invoke member functions of user classes).
  8. Incorrect Parameter Count: When defined as a member function, the LHS is passed implicitly via this, so the member operator must take exactly one parameter.
    • Fix:
      Complex operator+(const Complex& c2) {
          return Complex(real + c2.real, imag + c2.imag);
      }

Topic 7 Answers

  1. Early / Static, Late / Dynamic (The timing difference between compilation and execution matches).
  2. virtual (Instructs the compiler to defer function routing to runtime).
  3. Pure (A pure virtual function = 0 forces child implementations).
  4. VTable (virtual table), VPtr (virtual pointer) (The memory lookup components that enable dynamic dispatch).
  5. FALSE (Constructors cannot be virtual; objects must exist in memory before VPtrs can seek VTable indices).
  6. TRUE (Ensures derived subobjects are cleanly deallocated when deleted via base class pointers).
  7. B. Only the base class destructor is executed (Triggers early binding, completely bypassing derived class destructors and leaking heap blocks).
  8. Static Binding Issue: speak() is not declared virtual in the base class Animal. ptr->speak() will resolve statically and invoke the parent version.
    • Fix: Change Animal::speak() declaration to: virtual void speak() { ... }.

Topic 8 Answers

  1. tellg() (Returns the current read position byte offset).
  2. <iomanip> (Header file for parameterized manipulators).
  3. ios::in | ios::out (Bitwise OR binds read and write modes).
  4. -15 (Negative values seek backward from the current position pointer).
  5. FALSE (The width manipulator setw is temporary and deactivates immediately after printing the very next item).
  6. FALSE (Relative seeks with non-zero offsets on text-mode streams result in undefined behavior due to line-ending translations. It is only safe in binary mode).
  7. B. &&&&&&901 (setw(8) applies only to 90, padding it with 6 & characters. 1 is printed immediately next with zero padding).
  8. C. ios::failbit (Indicates non-fatal formatting failures, such as trying to read characters into an integer).
  9. Single Character Fill Bug: cout.fill() takes a single char parameter, not a double-quoted string literal.
    • Fix: Pass as a character literal: cout.fill('$');.