So I have this problem where the output prints the address of my pointer, I have no idea why this happens cuz the pointers is not modified at all
Heres the code:
using namespace std;
class AndroideAbstracto {
protected:
int *vida;
int *fuerza;
int *velocidad;
public:
void setvalores(int vi, int fu, int ve) {
velocidad = &ve;
vida = &vi;
fuerza = &fu;
};
virtual void imprimir(void) = 0;
};
class Androide : public AndroideAbstracto {
public:
void imprimir() {
std::cout << "Caracteristicas del androide:" << endl;
cout << "Velocidad = " << *velocidad << endl;
cout << "Vida = " << *vida << endl;
cout << "Fuerza = " << *fuerza << endl;
};
};
class Decorator : public AndroideAbstracto {
protected:
AndroideAbstracto *AndroideDec;
public:
Decorator(AndroideAbstracto* android_abs) {
AndroideDec = android_abs;
}
virtual void imprimir(void) = 0;
};
class Androide_Con_Habi : public Decorator {
protected:
string habilidad;
public:
Androide_Con_Habi(AndroideAbstracto* android_abs, string habi) : Decorator(android_abs) {
habilidad = habi;
}
virtual void imprimir() {
AndroideDec->imprimir();
cout << "La habilidad especial del androide es: " << habilidad << endl;
}
};
class Androide_Elegido : public Decorator {
protected:
bool elegido;
public:
Androide_Elegido(AndroideAbstracto *android_abs, bool es) : Decorator(android_abs) {
elegido = es;
}
virtual void imprimir() {
if (elegido) {
// *vida =(*vida) * 2; //Im quite new to C++ so im not really
// *fuerza *=2; //sure how should I multiply these pointers
// *velocidad *=2;
// AndroideDec->setvalores(vida*2,fuerza*2,velocidad*2);
AndroideDec->imprimir();
cout << "Este androide es uno de los elegidos";
}
}
};
int main(int argc, char *argv[]) {
Androide *andro = new Androide();
andro->setvalores(600, 700, 300);
andro->imprimir();
Androide_Con_Habi *andro_con_habi = new Androide_Con_Habi(andro, "Volar");
andro_con_habi->imprimir();
Androide_Elegido *superpoderoso = new Androide_Elegido(andro, true);
superpoderoso->imprimir();
delete superpoderoso;
delete andro;
delete andro_con_habi;
return 0;
}
I have no idea why but this prints:
Caracteristicas del androide:
Velocidad = 300
Vida = 600
Fuerza = 700
Caracteristicas del androide:
Velocidad = 300
Vida = 152436744
Fuerza = -1074718788
La habilidad especial del androide es: Volar
Caracteristicas del androide:
Velocidad = 300
Vida = 152436744
Fuerza = 1
Este androide es uno de los elegidos
The pointers to
vi,fu, andveget invalidated when the function returns. You’re not seeing addresses being printed, but simply garbage.Your entire design doesn’t and shouldn’t need to use pointers though.