Quick Answer
Master classes, inheritance, and polymorphism.
Understanding the Issue
C++ supports OOP with classes, encapsulation, inheritance, and polymorphism. Understanding these concepts is fundamental to C++ development.
The Problem
This code demonstrates the issue:
Cpp
Error
// Need to implement a basic class hierarchy
The Solution
Here's the corrected code:
Cpp
Fixed
#include <iostream>
#include <string>
// Base class
class Animal {
public:
Animal(const std::string& name) : name(name) {}
virtual void speak() const = 0; // Pure virtual function
protected:
std::string name;
};
// Derived class
class Dog : public Animal {
public:
Dog(const std::string& name) : Animal(name) {}
void speak() const override {
std::cout << name << " says Woof!" << std::endl;
}
};
int main() {
Dog myDog("Rex");
myDog.speak();
return 0;
}
Key Takeaways
Use classes, inheritance, and virtual functions for OOP in C++.