Doubt about Polymorphism and fixes in C ++

1

I have a question about the use of arrays with polymorphism, the subject is like this: I have a class Article that inherit two classes Book and CD.

class Articulo {

   protected:

     string nom;
   public:

     Articulo();
     virtual void mostrar() = 0;
}

class Libro : public Articulo{

   private:

     string autor;

   public:

     Libro();
     void mostrar();
     void verAutor();

}

class Cd : public Articulo{

   private:

     string compositor;

   public:

      Libro();
      void mostrar();
      void verCompositor();
}

Then I have a Business class that manages a vector of articles loaded with instances of book and CD.

class Negocio {

   private

     std::vector<Articulo*> vArticulos;

   public:

     Negocio();

     std::vector<Libro*> buscarPorAutor();
     std::vector<Cd*> buscarPorComp();

}

Within Business I have two methods of searching for articles by author (which returns books) and another by composer (returns cds) . As much in book as in cd I have methods to see the author and the composer, How I can know Of what instance is each element of the vector of articles?

    
asked by pepexito 31.10.2017 в 22:56
source

1 answer

1

You need to use dynamic_cast . I give you an example to extract the books:

std::vector<Libro*> seleccionarLibros()
{
  std::vector<Libro*> libros;
  for( size_t i=0; i<vArticulos.size(); i++ )
  {
    if( Libro* libro = dynamic_cast<Libro*>(vArticulos[i]) )
    {
      // Una vez obtenido el puntero puedes utilizarlo con normalidad
      libro->verAutor(); 
      libros.push_back(libro);
  }
  return libros;
}

dynamic_cast works as follows:

  • Can only be used with classes that have some type of inheritance. Otherwise, it fails at compile time.
  • Compile with RTTI enabled (usually a default option). Otherwise, it fails at compile time.
  • Can not be used to convert from an inherited type to another base (compile error). This conversion is automatic and does not require additional operations.
  • If the base pointer can be converted to the inherited type, it converts it, otherwise it returns a null pointer.
answered by 01.11.2017 / 00:19
source