inheritance - C++ how to destroy an object in the base class with a derived class constructor -
so in program have derived class called hangman , derived class called hangmangraphics. issue i'm having after game want reset variables reason base constructor not restarted or called. when run program go base constructor once towards end of program when:
#include "player.h" #include "hangman.h" #include "hangmangraphics.h" using namespace std; int main() { hangmangraphics game2; while(1) { game2.play(); if(game2.play()=='y') { game2=hangmangraphics(); //in part of code want reset base //constructor values how do using //derived construtor continue; } } }
cheap hack. moving definition of game2 while loop provide new game2 every pass though loop:
int main() { while(1) { hangmangraphics game2; // game2 created here // stuff } // game2 destroyed here }
there not enough information provided in question whether thing or bad. but...
game2=hangmangraphics();
will 5 things:
- call hangmangraphics's constructor create temporary hangmangraphics.
- this results in call hangman's constructor
- call hangmangraphics's = operator. if 1 has not been specified, default copy contents of right hand hangmangraphics left. copy pointer, not pointed-to data.
- call destructor on temporary hangmangraphics
- which results in call hangman's destructor
if have dynamically allocated storage in hangmangraphics or hangman, need read on rule of three
anything dynamically allocated within temporary hangmangraphics , it's base hangman (or should have been) deleted destructor. if operator= not custom-defined handle dynamic data, game2 contains pointers invalid storage.
example:
class base { public: base(): baseval(number++), interestingdata(new int(number++)) { cout << "base ctor " << baseval << "," << * interestingdata <<endl; } virtual ~base() { cout << "base dtor " << baseval << "," << * interestingdata <<endl; delete interestingdata; } private: int baseval; int * interestingdata; }; class derived: public base { public: derived():base() { cout << "derived ctor" <<endl; } virtual ~derived() { cout << "derived dtor" <<endl; } derived & operator=(const derived & rhs) //only exists cout { cout << "derived =" <<endl; base::operator=(rhs); return *this; } }; int main() { derived test; cout << "created test" << endl; test = derived(); cout << "exit" << endl; }
output
base ctor 0,1 derived ctor created test base ctor 2,3 derived ctor derived = derived dtor base dtor 2,3 exit derived dtor base dtor 2,4067440
interestingdata in last print smashed because address points has been reassigned. more fun, deleted second time , should crash program.
Comments
Post a Comment