0% found this document useful (0 votes)
17 views

Code

code
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views

Code

code
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 1

#include <iostream>

#include <string> int main() {


// Creating an Animal object
// Base class Animal animal("Generic Animal");
class Animal { animal.makeSound(); // Output:
Generic Animal makes a sound.
protected:
std::string name;
// Creating a Dog object
Dog dog("Buddy");
public:
dog.makeSound(); // Output: Buddy
// Constructor
barks.
Animal(std::string n) : name(n) {}

return 0;
// Method to make sound
}
virtual void makeSound() {
std::cout << name << " makes a
sound." << std::endl;
}

Explanation:
// Method to get the name
Base Class (Animal):
std::string getName() {
return name;
Contains a protected member variable
}
name to store the name of the animal.
};
Has a constructor to initialize the
name.

// Derived class Includes a virtual method


makeSound() that can be overridden
class Dog : public Animal { in derived classes.
public: Derived Class (Dog):
// Constructor
Dog(std::string n) : Animal(n) {} Inherits from the Animal class.
Overrides the makeSound() method to
// Overriding the makeSound provide specific behavior for dogs.
method Main Function:
void makeSound() override {
std::cout << name << " barks." Creates an instance of Animal and
<< std::endl; Dog, demonstrating polymorphism by
} calling the overridden method.

};

You might also like