0
0
C++programming~30 mins

Interface-like behavior in C++ - Mini Project: Build & Apply

Choose your learning style9 modes available
Interface-like Behavior in C++
πŸ“– Scenario: Imagine you are building a simple program to manage different types of devices that can be turned on and off. Each device should have a way to turn it on and off, but the exact way might be different for each device.
🎯 Goal: You will create a basic interface-like behavior in C++ using abstract classes. You will define a class with pure virtual functions and then create classes that implement these functions. Finally, you will use these classes to turn devices on and off.
πŸ“‹ What You'll Learn
Create an abstract class called Device with two pure virtual functions: turnOn() and turnOff().
Create a class called Light that inherits from Device and implements turnOn() and turnOff().
Create a class called Fan that inherits from Device and implements turnOn() and turnOff().
Create a pointer of type Device* to point to objects of Light and Fan and call their turnOn() and turnOff() methods.
Print messages to show which device is turning on or off.
πŸ’‘ Why This Matters
🌍 Real World
Many programs use interface-like behavior to handle different objects in a uniform way, such as controlling various hardware devices or managing different types of user inputs.
πŸ’Ό Career
Understanding abstract classes and polymorphism is essential for software development jobs, especially in C++ programming for systems, games, and applications requiring flexible design.
Progress0 / 4 steps
1
Create the abstract class Device
Create an abstract class called Device with two pure virtual functions: turnOn() and turnOff(). Both functions should return void and have no parameters.
C++
Need a hint?

Use virtual keyword and = 0 to make functions pure virtual.

2
Create the Light class inheriting Device
Create a class called Light that inherits from Device. Implement the turnOn() method to print "Light is turned ON" and the turnOff() method to print "Light is turned OFF".
C++
Need a hint?

Use override keyword to show you are implementing the base class methods.

3
Create the Fan class inheriting Device
Create a class called Fan that inherits from Device. Implement the turnOn() method to print "Fan is turned ON" and the turnOff() method to print "Fan is turned OFF".
C++
Need a hint?

Follow the same pattern as the Light class for Fan.

4
Use Device pointers to control Light and Fan
Create a Device* pointer called device. Point it to a Light object and call turnOn() and turnOff(). Then point device to a Fan object and call turnOn() and turnOff(). Print the output.
C++
Need a hint?

Use a pointer of type Device* to point to objects of Light and Fan. Call their methods using the pointer.