Ejemplo de Herencia en C++. POO.

C++:
  1. #include <iostream.h>
  2. #include <stdlib.h>
  3.  
  4. class Padre
  5. {
  6.     protected:
  7.       char* _nombre;
  8.       int _edad;
  9.  
  10.     public:
  11.       Padre():_edad(-1)
  12.       {
  13.         _nombre = new char[20];
  14.         strcpy(_nombre, "Default");
  15.       }
  16.       Padre(char* n, int a = 1):_edad(a)
  17.       {
  18.         _nombre = new char[20];
  19.         strcpy(_nombre, n);
  20.       }
  21.  
  22.       inline int edad()const { return _edad; }
  23.       char* nombre() const
  24.       {
  25.         char* temp = new char[20];
  26.         strcpy(temp, _nombre);
  27.         return temp;
  28.       }                                                                             
  29.  
  30.       friend ostream& operator <<(ostream& out, const Padre& rhs)
  31.       {
  32.          out <<"nombre: " <<rhs.nombre() <<" edad: " <<rhs.edad();
  33.          return out;
  34.       }
  35. };
  36.  
  37. class Hijo : public Padre
  38. {
  39.       protected:
  40.             int _matricula;
  41.             char* _escuela;
  42.      public:
  43.  
  44.             Hijo(char* nombrePadre, int edadPadre, char* nEscuela, int nMatricula): Padre(nombrePadre, edadPadre)
  45.             {
  46.                _matricula = nMatricula;
  47.                _escuela = new char[20];
  48.                strcpy(_escuela, nEscuela);
  49.             }
  50.  
  51.             inline int matricula(){ return _matricula; }
  52.  
  53.             char* escuela()
  54.             {
  55.                char* temp = new char[20];
  56.                strcpy(temp, _escuela);
  57.                return temp;
  58.             }
  59.  
  60.             friend ostream& operator <<(ostream& out, const Hijo &rhs)
  61.             {
  62.                 out <<static_cast<Padre> (rhs) <<" escuela: " <<rhs._escuela <<" matricula : " <<rhs._matricula;
  63.                 return out;
  64.             }
  65. };
  66.  
  67. int main(int args, char** argv)
  68. {
  69.        bool cond = false;
  70.        if(args == 2)
  71.              cond = !strcmp(argv[1], "-debug");
  72.  
  73.       if(cond) cout <<"Creando objeto Padre " <<endl;
  74.       Padre p1("Alejandro", 24);
  75.  
  76.       if(cond) cout <<"Creando objeto Hijo " <<endl;
  77.       Hijo h1("Junior", 15, "Tec", 922382);
  78.  
  79.       cout <<p1 <<endl;
  80.       cout <<h1 <<endl;
  81.       system("PAUSE");
  82.       return 0;
  83. }

Popularidad: 14%