Hello,
Is it possible to "update" an object in this sense?
I have an object of Base class and pointers to this object. Finally I
would like to replace this object by an object of Derived class and all
pointer contain the address of the new object. Here is an unsucsessful
attempt to do it.
#include <iostream>
using namespace std;
class Base {
public:
Base();
virtual void speak();
};
class Derived: public Base {
public:
Derived();
virtual void speak();
};
Base::Base() {
}
void Base::speak() {
cout << "I am an object of class Base" << '\n';
}
Derived::Derived() {
}
void Derived::speak() {
cout << "I am an object of class Derived" << '\n';
}
int main () {
Derived objD;
Base* p1 = new Base();
Base* p2 = p1;
Derived* z = new Derived; //new class
*p1 = *z; //it is assign and the result is a Base class
p1->speak();//does not work, it is still Base class
return 0;
}