Cosider this little program:
Code:
#include <iostream>
using namespace std;
class figura {
public:
int j;
virtual void imprime() =0;
//constructor
figura () : j(3) { }
};
class d_figura2 : public figura {
public:
virtual void imprime() { cout << j << endl; }
//method
void muda() { j = 9; }
};
class d_figura3 : public figura {
public:
int retorna() { return j; }
};
int main () {
figura *minhafigura;
d_figura2 minhafigura2;
d_figura3 *minhafigura3;
minhafigura2.imprime(); // prints the number 3 (j=3)
minhafigura2.muda(); // change j=3 to j=9
minhafigura2.imprime(); // now prints the number 9 (j=9)
minhafigura = &minhafigura2;
minhafigura->imprime(); // prints the number 9 again (j=9)
/*
* Now I want to use the method retorna() from class d_figura3.
* But, I need to do that from the object minhafigura2,
* because of its previous definitions, e.g., variable j.
* What am I suppose to do?
*/
// thought something like that:
minhafigura = minhafigura3;
minhafigura3->retorna();
// of course, it didn't work because *minhafigura3 isn't an object, so it was not initialized
return 0;
}
Could anyone help me on that?
Thanks