logo

Crowdly

Browser

Додати до Chrome

You will refactor the design from Part (a) so that the formatting behaviour is i...

✅ Перевірена відповідь на це питання доступна нижче. Наші рішення, перевірені спільнотою, допомагають краще зрозуміти матеріал.

You will refactor the design from Part (a) so that the formatting behaviour is implemented using

runtime polymorphism (virtual functions) rather than checking a kind string.

Goal: No if/else/switch may be used to select the message-type behaviour.

Required output format rules:

  • Email: EMAIL to <user>: <text>
  • SMS: SMS to <user>: <text> (truncate text to 20 characters)
  • Push: PUSH to <user>: <optional URGENT><text>

    (if priority ≥ 4, add

    URGENT before the text)

Task:

Complete the code template below by writing the missing class hierarchy.

You must only fill the

TODO sections.

#include <iostream>

#include <string>

#include <memory>

#include <array>

using namespace std;

// =====================

// TODO 1: Base class

// =====================

// Create an abstract class named MessageBase with:

// - a virtual destructor

// - virtual string format() const = 0;

// =====================

// TODO 2: Derived classes

// =====================

// Implement these derived classes (each must override format()):

// - EmailMessage

// - SMSMessage

// - PushMessage

//

// Each derived class should store the data it needs (user, text, priority if needed).

// Do NOT store a "kind" field in the polymorphic design.

int main() {

// Do not change main()

array<unique_ptr<MessageBase>, 3> msgs = {

make_unique<EmailMessage>("u100", "Welcome to the system", 2),

make_unique<SMSMessage>("u101", "Your verification code is 123456", 3),

make_unique<PushMessage>("u102", "Server maintenance tonight", 5)

};

for (const auto& m : msgs) {

cout << m->format() << "\n";

}

}

Expected output:

EMAIL to u100: Welcome to the system

SMS to u101: Your verification code

PUSH to u102: URGENT Server maintenance tonight

Constraints (must follow):

  • No conditional logic (if/else/switch) is allowed to select the message type behavior.
  • No dynamic_cast and no typeid.
  • Use the provided array<unique_ptr<MessageBase>> to demonstrate polymorphism.
Більше питань подібних до цього

Хочете миттєвий доступ до всіх перевірених відповідей на moodle.uleth.ca?

Отримайте необмежений доступ до відповідей на екзаменаційні питання - встановіть розширення Crowdly зараз!

Browser

Додати до Chrome