[ create a new paste ] login | about

Link: http://codepad.org/OcBMVud2    [ raw code | output | fork ]

salvador@conclase.net - C++, pasted on Sep 16:
#include <cstring>
#include <iostream>

using namespace std;

class Cadena {
  public:
   Cadena(const char *cad);
   Cadena() : cadena(0) { cout << "Constructor sin parametros" << endl; };
   Cadena(const Cadena &c);
   ~Cadena();
   Cadena &operator=(const Cadena &c);
   Cadena operator+(const Cadena &);

   void Mostrar() const;
  private:
   char *cadena;
};

Cadena::Cadena(const char *cad) {
   cadena = new char[strlen(cad)+1];
   strcpy(cadena, cad);
   cout << "Constructor (" << cad <<") [" << (void*)cadena << "]" << endl;
}

Cadena::Cadena(const Cadena &c) {
    cadena = new char[strlen(c.cadena)+1];
    strcpy(cadena, c.cadena);
    cout << "Constructor copia (" << cadena << ") [" << (void*)cadena << "]" << endl;
}

Cadena::~Cadena() { 
   cout << "Destructor (" << cadena << ") [" << (void*)cadena << "]" << endl; 
   delete[] cadena; 
}

void Cadena::Mostrar() const {
   cout << cadena << endl;
}

Cadena &Cadena::operator=(const Cadena &c) {
   cout << "Asignacion" << endl;
   if(this != &c) {
      delete[] cadena;
      if(c.cadena) {
         cadena = new char[strlen(c.cadena)+1];
         strcpy(cadena, c.cadena);
      }
      else cadena = 0;
   }
   return *this;
}

Cadena Cadena::operator+(const Cadena &c) {
   cout << "suma-";
   Cadena temp;

   temp.cadena = new char[strlen(c.cadena)+strlen(this->cadena)+1];
   strcpy(temp.cadena, this->cadena);
   strcat(temp.cadena, c.cadena);
   return temp;
}

int main() {
    Cadena C1("Hola"), C2("Adios"), C3("");

    C3 = C1 + ", mundo!";
    C3.Mostrar();
    (C2+", mundo").Mostrar();
    return 0;
}


Output:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
Constructor (Hola) [0x8051438]
Constructor (Adios) [0x8051568]
Constructor () [0x8051590]
Constructor (, mundo!) [0x80515b0]
suma-Constructor sin parametros
Constructor copia (Hola, mundo!) [0x80515d8]
Destructor (Hola, mundo!) [0x80514e8]
Asignacion
Destructor (Hola, mundo!) [0x80515d8]
Destructor (, mundo!) [0x80515b0]
Hola, mundo!
Constructor (, mundo) [0x80515b0]
suma-Constructor sin parametros
Constructor copia (Adios, mundo) [0x8051608]
Destructor (Adios, mundo) [0x80515d8]
Adios, mundo
Destructor (Adios, mundo) [0x8051608]
Destructor (, mundo) [0x80515b0]
Destructor (Hola, mundo!) [0x80514e8]
Destructor (Adios) [0x8051568]
Destructor (Hola) [0x8051438]


Create a new paste based on this one


Comments: