OOP in C++: An Introduction to Classes, Objects, and Inheritance - Biz Tech

OOP in C++: An Introduction to Classes, Objects, and Inheritance

Listen
 #include <iostream>
#include <string>

// Base class: Animal
class Animal {
public:
    Animal(const std::string& name) : name(name) {}

    void speak() const {
        std::cout << name << " says: " << sound << std::endl;
    }

protected:
    std::string name;
    std::string sound;
};

// Derived class: Dog
class Dog : public Animal {
public:
    Dog(const std::string& name) : Animal(name) {
        sound = "Woof!";
    }
};

// Derived class: Cat
class Cat : public Animal {
public:
    Cat(const std::string& name) : Animal(name) {
        sound = "Meow!";
    }
};

int main() {
    Dog dog("Buddy");
    Cat cat("Whiskers");

    dog.speak();
    cat.speak();

    return 0;
}
 

This code block demonstrates an introduction to Object-Oriented Programming (OOP) in C++ using classes, objects, and inheritance. The program defines a base class Animal with a member function speak() and two derived classes Dog and Cat, which inherit from the base class. The derived classes override the sound member variable to customize the output for each animal type. In the main function, objects of both derived classes are created and their speak() member functions are called.