Bird
Raised Fist0
C++programming~20 mins

Object interaction in C++ - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
πŸŽ–οΈ
Object Interaction Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of method interaction between objects
What is the output of the following C++ code involving two interacting objects?
C++
#include <iostream>
using namespace std;

class Engine {
public:
    int power;
    Engine(int p) : power(p) {}
    int getPower() { return power; }
};

class Car {
public:
    Engine engine;
    Car(int p) : engine(p) {}
    void showPower() {
        cout << "Power: " << engine.getPower() << endl;
    }
};

int main() {
    Car car(150);
    car.showPower();
    return 0;
}
A
Power: 150
B
Power: 0
C
Compilation error due to missing default constructor
D
Runtime error due to uninitialized engine
Attempts:
2 left
πŸ’‘ Hint
Check how the Engine object is initialized inside the Car constructor.
🧠 Conceptual
intermediate
2:00remaining
Understanding object references in method calls
Consider two classes where one object calls a method on another object passed by reference. What is the effect of modifying the passed object inside the method?
C++
class Box {
public:
    int length;
    Box(int l) : length(l) {}
    void doubleLength() { length *= 2; }
};

class Worker {
public:
    void process(Box &b) {
        b.doubleLength();
    }
};

int main() {
    Box box(5);
    Worker w;
    w.process(box);
    // What is box.length now?
}
A10
B5
CCompilation error due to missing const
DUndefined behavior due to dangling reference
Attempts:
2 left
πŸ’‘ Hint
Passing by reference allows the method to modify the original object.
πŸ”§ Debug
advanced
3:00remaining
Identify the cause of runtime error in object interaction
This code compiles but crashes at runtime. What causes the crash?
C++
#include <iostream>
using namespace std;

class Node {
public:
    int value;
    Node* next;
    Node(int v) : value(v), next(nullptr) {}
};

class List {
public:
    Node* head;
    List() : head(nullptr) {}
    void add(int v) {
        Node n(v);
        n.next = head;
        head = &n;
    }
    void print() {
        Node* current = head;
        while(current) {
            cout << current->value << " ";
            current = current->next;
        }
        cout << endl;
    }
};

int main() {
    List l;
    l.add(10);
    l.add(20);
    l.print();
    return 0;
}
AThe Node constructor is missing initialization of next pointer
BThe head pointer is never initialized causing null pointer dereference
CThe add method stores address of a local variable which is destroyed after add returns
DThe print method modifies the list causing infinite loop
Attempts:
2 left
πŸ’‘ Hint
Local variables inside functions are destroyed when the function ends.
πŸ“ Syntax
advanced
2:00remaining
Correct syntax for object interaction with pointers
Which option correctly creates two objects and makes one object call a method on the other using pointers?
C++
class Printer {
public:
    void printMessage() { std::cout << "Hello" << std::endl; }
};

int main() {
    Printer* p1 = new Printer();
    Printer* p2 = new Printer();
    // Call printMessage of p1 using p2
}
Ap2->printMessage();
Bp1->printMessage();
Cp2->p1->printMessage();
D(*p2).p1.printMessage();
Attempts:
2 left
πŸ’‘ Hint
Use the arrow operator to call methods on pointers.
πŸš€ Application
expert
3:00remaining
Determine the final state of interacting objects after method calls
Given these classes, what is the final value of the counter in the Manager object after main runs?
C++
#include <iostream>
using namespace std;

class Worker {
public:
    int id;
    Worker(int i) : id(i) {}
    void doWork(int &counter) {
        counter += id;
    }
};

class Manager {
public:
    int counter = 0;
    void assignWork(Worker &w) {
        w.doWork(counter);
    }
};

int main() {
    Manager m;
    Worker w1(3), w2(7);
    m.assignWork(w1);
    m.assignWork(w2);
    cout << m.counter << endl;
    return 0;
}
A3
B0
C7
D10
Attempts:
2 left
πŸ’‘ Hint
The Manager's counter is updated by adding each Worker's id.

Practice

(1/5)
1. What does it mean when one object calls a method on another object in C++?
easy
A. The first object is asking the second object to perform an action.
B. The first object copies the second object's data.
C. The first object deletes the second object.
D. The first object creates a new object inside the second object.

Solution

  1. Step 1: Understand method calls between objects

    When one object calls a method on another, it requests that object to do something or provide information.
  2. Step 2: Differentiate from other actions

    Copying data, deleting, or creating objects are different operations, not the same as calling a method.
  3. Final Answer:

    The first object is asking the second object to perform an action. -> Option A
  4. Quick Check:

    Object method call = request action [OK]
Hint: Method call means asking another object to do something [OK]
Common Mistakes:
  • Confusing method call with copying data
  • Thinking method call deletes objects
  • Assuming method call creates new objects inside others
2. Which of the following is the correct syntax to pass an object obj of class Car to a method drive of another object driver?
easy
A. driver.drive(obj);
B. drive.driver(obj);
C. driver->drive(obj);
D. drive(obj).driver;

Solution

  1. Step 1: Identify correct method call syntax

    For an object driver, calling method drive with argument obj uses dot notation: driver.drive(obj);
  2. Step 2: Eliminate incorrect syntax

    drive.driver(obj); reverses object and method, driver->drive(obj); is for pointers, and drive(obj).driver; is invalid.
  3. Final Answer:

    driver.drive(obj); -> Option A
  4. Quick Check:

    Object.method(argument) = driver.drive(obj) [OK]
Hint: Use object.method(argument) syntax for calling methods [OK]
Common Mistakes:
  • Using arrow operator on non-pointer objects
  • Swapping method and object names
  • Incorrect punctuation or order
3. What is the output of this code?
#include <iostream>

class Light {
public:
    void turnOn() { std::cout << "Light is ON" << std::endl; }
};

class Switch {
public:
    void press(Light &l) { l.turnOn(); }
};

int main() {
    Light roomLight;
    Switch wallSwitch;
    wallSwitch.press(roomLight);
    return 0;
}
medium
A. Compilation error
B. Light is OFF
C. No output
D. Light is ON

Solution

  1. Step 1: Understand method call inside press()

    The press method calls turnOn() on the passed Light object, which prints "Light is ON".
  2. Step 2: Trace main function calls

    wallSwitch.press(roomLight); calls turnOn() on roomLight, so output is "Light is ON".
  3. Final Answer:

    Light is ON -> Option D
  4. Quick Check:

    Method call prints "Light is ON" [OK]
Hint: Method calls inside other methods print output [OK]
Common Mistakes:
  • Assuming no output because press() returns void
  • Confusing reference passing with copying
  • Thinking code causes compilation error
4. Identify the error in this code snippet:
#include <iostream>

class Engine {
public:
    void start() { std::cout << "Engine started" << std::endl; }
};

class Car {
public:
    void ignite(Engine e) { e.start(); }
};

int main() {
    Engine myEngine;
    Car myCar;
    myCar.ignite(myEngine);
    return 0;
}
medium
A. Method start() is not declared correctly.
B. Car class should inherit from Engine.
C. Passing Engine by value causes unnecessary copying.
D. Cannot call start() on Engine object.

Solution

  1. Step 1: Analyze parameter passing in ignite()

    The method ignite takes Engine e by value, which copies the object unnecessarily.
  2. Step 2: Suggest improvement

    Passing by reference (Engine &e) avoids copying and is more efficient.
  3. Final Answer:

    Passing Engine by value causes unnecessary copying. -> Option C
  4. Quick Check:

    Pass objects by reference to avoid copying [OK]
Hint: Pass objects by reference to avoid copies [OK]
Common Mistakes:
  • Thinking method start() is incorrect
  • Assuming inheritance is required
  • Believing start() cannot be called on Engine
5. Given classes Teacher and Student, how can you design a method in Teacher that lets a teacher assign a grade to a student object? Choose the best approach.
hard
A. Make Student inherit from Teacher and override a grade method.
B. Define a method in Teacher that takes a Student reference and an int grade, then calls a Student method to set the grade.
C. Store grades only inside Teacher without involving Student objects.
D. Use global variables to store grades for all students.

Solution

  1. Step 1: Understand object interaction for assigning grades

    The Teacher should interact with Student by calling a method on Student to set the grade, passing the grade value.
  2. Step 2: Evaluate options

    Define a method in Teacher that takes a Student reference and an int grade, then calls a Student method to set the grade. correctly uses a method in Teacher that takes a Student reference and grade, then calls Student's method to set the grade. Other options misuse inheritance, ignore object interaction, or use bad global state.
  3. Final Answer:

    Define a method in Teacher that takes a Student reference and an int grade, then calls a Student method to set the grade. -> Option B
  4. Quick Check:

    Teacher calls Student method to assign grade [OK]
Hint: Teacher calls Student method with grade parameter [OK]
Common Mistakes:
  • Misusing inheritance for unrelated roles
  • Ignoring encapsulation by using globals
  • Storing grades only in Teacher without Student update
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard