Group
Object-Oriented Programming in C++
Objective
1. Define a base class called "Animal" with two methods: makeSound and move.
2. Implement the makeSound method to output a generic sound and the move method to output a generic movement.
3. Create two derived classes: "Dog" and "Cat", which inherit from the "Animal" class.
4. Override the makeSound and move methods in both the Dog and Cat classes to reflect their specific behavior.
5. In the main function, create instances of Dog and Cat, and call the makeSound and move methods for each.
Write an Animal class with makeSound and move methods, and then create derived classes like Dog and Cat.
Example C++ Exercise
Show C++ Code
#include <iostream> // Include the standard input/output library
using namespace std;
// Define the base class 'Animal'
class Animal {
public:
// Method to make a sound (generic)
virtual void makeSound() {
cout << "The animal makes a sound." << endl;
}
// Method to move (generic)
virtual void move() {
cout << "The animal moves." << endl;
}
// Virtual destructor
virtual ~Animal() {}
};
// Define the derived class 'Dog' which inherits from 'Animal'
class Dog : public Animal {
public:
// Override makeSound method for Dog
void makeSound() override {
cout << "The dog barks." << endl;
}
// Override move method for Dog
void move() override {
cout << "The dog runs." << endl;
}
};
// Define the derived class 'Cat' which inherits from 'Animal'
class Cat : public Animal {
public:
// Override makeSound method for Cat
void makeSound() override {
cout << "The cat meows." << endl;
}
// Override move method for Cat
void move() override {
cout << "The cat walks gracefully." << endl;
}
};
int main() {
// Create a Dog object and call its methods
Dog myDog;
myDog.makeSound(); // Dog-specific sound
myDog.move(); // Dog-specific movement
// Create a Cat object and call its methods
Cat myCat;
myCat.makeSound(); // Cat-specific sound
myCat.move(); // Cat-specific movement
return 0; // Return 0 to indicate successful execution
}
Output
The dog barks.
The dog runs.
The cat meows.
The cat walks gracefully.