Nuestros desarrolladores estrellas agotaron sus depósitos de café, por su búsqueda día y noche por la resolución, hasta que José encontró el hallazgo en Gitea así que ahora la compartimos contigo.
Ejemplo: ¿Cuál es el significado de herencia en C++? Escribe un ejemplo de herencia simple.
Inheritance is one of the key features of Object-oriented programming in C++.
It allows us to create a newclass(derived class) from an existing class(base class).
The derived classinherits the features from the base classand can have additional features of its own.
For example,classAnimal// eat() function// sleep() function;classDog:publicAnimal// bark() function;
Here, the Dog classis derived from the Animal class.
Since Dog is derived from Animal, members of Animal are accessible to Dog.
Notice the use of the keyword publicwhile inheriting Dog from Animal.classDog:publicAnimal...;
We can also use the keywords privateandprotected instead of public
Example:// C++ program to demonstrate inheritance#include usingnamespace std;// base classclassAnimalpublic:voideat()
cout <<"I can eat!"<< endl;voidsleep()
cout <<"I can sleep!"<< endl;;// derived classclassDog:publicAnimalpublic:voidbark()
cout <<"I can bark! Woof woof!!"<< endl;;intmain()// Create object of the Dog class
Dog dog1;// Calling members of the base class
dog1.eat();
dog1.sleep();// Calling member of the derived class
dog1.bark();return0;
Output
I can eat!
I can sleep!
I can bark! Woof woof!!
Here,dog1(the object of derived classDog) can access members of the base classAnimal.
It's because Dog is inherited from Animal.
Te mostramos las reseñas y valoraciones de los usuarios
Te invitamos a asentar nuestra tarea ejecutando un comentario y puntuándolo te lo agradecemos.
¡Haz clic para puntuar esta entrada!
(Votos: 0 Promedio: 0)