Start learning free

LESSON 616 OF 634 · OBJECT-ORIENTED PROGRAMMING - CHALLENGES

Car and Engine in C++

Practice O(1)

You build two classes, Engine and Car. A car has an engine and passes work on to it.

Implement:

  • Engine(horsepower) makes an engine with that power.
  • The engine's start() returns "Engine with H hp started", with its power as H.
  • Car(name, engine) makes a car that has this engine.
  • The car's start() returns its name and ": " before the engine's start() text.
  • swapEngine(engine) puts a new engine in the car.
  • horsepower() returns the power of the car's engine.

The starter code spells every name the way your language does.

Each test makes some cars and calls their methods. Every start and horsepower result is printed on its own line.

 

Example 1:

Input:
    car = Car("Rocket", Engine(150))
    car.start()
    car.horsepower()
Output:
Rocket: Engine with 150 hp started
150
Explanation: Rocket's engine has 150 hp.
The car puts "Rocket: " before the engine's text.

Example 2:

Input:
    car = Car("Bolt", Engine(90))
    car.start()
    car.horsepower()
    car.swapEngine(Engine(300))
    car.start()
    car.horsepower()
Output:
Bolt: Engine with 90 hp started
90
Bolt: Engine with 300 hp started
300
Explanation: After the swap, Bolt has the 300 hp engine.
Its name stays the same.

Example 3:

Input:
    Engine(7).start()
    car = Car("Ant", Engine(1))
    car.swapEngine(Engine(1000))
    car.horsepower()
Output:
Engine with 7 hp started
1000
Explanation: An engine can start on its own.
Its text has no car name.
Ant's first engine is replaced before any call.

 

Constraints:

  • Each power is a whole number from 1 to 1,000.
  • A name is one word of 1 to 10 letters.
  • The cars in a test have different names.
  • At most 5 cars and 100 calls per test.
STEP 1 OF 9
    Ctrl + Enter to check

    Car And Engine in C++

    Keep going with C++500+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free