estoy aprendiendo como funciona la herencia y el polimorfismo,mi problema es que no entiendo porque pasa lo siguiente:
Gato es un objeto de tipo DomesticCat
que hereda de la clase Feline
al heredar de esta clase hereda los metodos que esta tiene y los que heredó de Mammal
,mi duda es la siguiente:
¿Porque el objeto de tipo Gato puede hacer uso de los metodos set_circus_name
y get_circus_name
?
entiendo que la clase Gato hereda estos metodos pero al crear un objeto de tipo gato se usa el segundo constructor de la clase Feline
el cual no inicializa el atributo Circus_name
que es necesario para que estas 2 funciones funcionen, sin embargo si se llaman estas 2 funciones usando un objeto de tipo Gato
funcionan sin ningun problema
main.cpp
#include <iostream>
#include "DomesticCat.h"
int main(int argc, char** argv) {
DomesticCat* Gato = new DomesticCat(2015,"Montevideo","Gato Persa","Franco");
Gato->set_circus_name("Circo");
std::cout<<Gato->get_circus_name();
return 0;
}
Feline.h
#include "Mammal.h"
class Feline : public Mammal{
private:
std::string Circus_name;
public:
Feline(int birth_year,std::string birth_place,std::string breed,std::string Circus_name) : Mammal(birth_year,birth_place,breed){
this->Circus_name = Circus_name;
}
Feline(int birth_year,std::string birth_place,std::string breed) : Mammal(birth_year,birth_place,breed){};
std::string print_diet(){
return "La dieta del felino es a base de carne\n";
}
void set_circus_name(std::string new_circus_name){
this->Circus_name = new_circus_name;
}
std::string get_circus_name(){
return Circus_name;
}
~Feline(){
}
};
#endif
DomesticCat.h
#include <iostream>
#include "Feline.h"
class DomesticCat : public Feline{
private:
std::string Owners_name;
public:
DomesticCat(int birth_year,std::string birth_place,std::string breed,std::string Owners_name) : Feline(birth_year,birth_place,breed){
this->Owners_name = Owners_name;
}
std::string print_diet(){
return "La dieta del gato es con Whiskas\n";
}
void set_owners_name(std::string Owners_name){
this->Owners_name = Owners_name;
}
std::string get_owners_name(){
return Owners_name;
}
~DomesticCat(){
}
};