Objective: Write
a C++ program to illustrate the concept of inheritance.
Code:
#include <iostream>
using namespace std;
// Base class
class Animal {
public:
void eat() {
cout << "This animal eats food." << endl;
}
};
// Derived class inheriting from Animal
class Dog : public Animal {
public:
void bark() {
cout << "The dog barks." << endl;
}
};
int main() {
// Creating an object of the derived class
Dog myDog;
// Calling the base class method using the derived class object
myDog.eat();
// Calling the derived class method
myDog.bark();
return 0;
}
Output:
No comments:
Post a Comment