inheritance sample example c++
Example 1: inheritance in c++
#include <iostream>
class Entity {
public:
float x =0 , y = 0;
void Move(float xa, float ya) {
x += xa;
y += ya;
}
};
class Player:public Entity
{
public :
const char* name = nullptr;
void Print() {
std::cout << name << std::endl;
}
};
int main()
{
Player D;
D.x = 5.5f;
D.y = 4.4f;
D.Move(1.1f,2.2f);
D.name = "Caleb";
D.Print();
std::cout <<"Size of Entity was : " << sizeof(Entity) << std::endl;
std::cout <<"Size of Player was : "<< sizeof(Player) << std::endl;
std::cin.get();
}
Example 2: What is the meaning of inheritance in C++. Write an example of simple inheritance.
Inheritance is one of the key features of Object-oriented programming in C++.
It allows us to create a new class (derived class) from an existing class (base class).
The derived class inherits the features from the base class and can have additional features of its own.
For example,
class Animal {
};
class Dog : public Animal {
};
Here, the Dog class is derived from the Animal class.
Since Dog is derived from Animal, members of Animal are accessible to Dog.
Notice the use of the keyword public while inheriting Dog from Animal.
class Dog : public Animal {...};
We can also use the keywords private and protected instead of public
Example:
#include <iostream>
using namespace std;
class Animal {
public:
void eat() {
cout << "I can eat!" << endl;
}
void sleep() {
cout << "I can sleep!" << endl;
}
};
class Dog : public Animal {
public:
void bark() {
cout << "I can bark! Woof woof!!" << endl;
}
};
int main() {
Dog dog1;
dog1.eat();
dog1.sleep();
dog1.bark();
return 0;
}
Output
I can eat!
I can sleep!
I can bark! Woof woof!!
Here, dog1 (the object of derived class Dog) can access members of the base class Animal.
It's because Dog is inherited from Animal.