In C++, there is no direct interface keyword like in some other languages (e.g., Java or C#), but you can create an interface using an abstract class that contains only pure virtual functions.
An interface defines a contract that derived classes must follow by implementing all the pure virtual functions.
#include <iostream>
using namespace std;
// Interface declaration
class IAnimal {
public:
virtual void makeSound() = 0; // Pure virtual function
virtual void move() = 0; // Pure virtual function
virtual ~IAnimal() {} // Virtual destructor for cleanup
};
class Dog : public IAnimal {
public:
void makeSound() override {
cout << "Dog says: Woof Woof!" << endl;
}
void move() override {
cout << "Dog runs" << endl;
}
};
class Bird : public IAnimal {
public:
void makeSound() override {
cout << "Bird says: Tweet Tweet!" << endl;
}
void move() override {
cout << "Bird flies" << endl;
}
};
int main() {
IAnimal* animal1 = new Dog();
IAnimal* animal2 = new Bird();
animal1->makeSound();
animal1->move();
animal2->makeSound();
animal2->move();
delete animal1;
delete animal2;
return 0;
}
Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!