c++ - pointer problems with inherited class -
in below code secclass inheriting 'item' firstclass. when run 'classc' in main both first item , second item 210. if remove pointer inherited class(firstclass), runs should. i'm still rather shaky both pointers , inheritance there's i'm missing here...
// declaration of firstclass // firstclass.h #include <iostream> #ifndef firstclass_h #define firstclass_h using namespace std; class firstclass { private: int *item; public: firstclass(); firstclass(int thatitem); ~firstclass(); int getitem(); void setitem(int thatitem); }; #endif // implementation of firstclass.h // firstclass.cpp #include "firstclass.h" using namespace std; firstclass::firstclass() { int *setinitial = new int; *setinitial = 5; item = setinitial; } firstclass::firstclass(int thatitem) { item = &thatitem; } firstclass::~firstclass(){} int firstclass::getitem() { return *item; } void firstclass::setitem(int thatitem) { item = &thatitem; } // declaration of secclass // secclass.h #ifndef secclass_h #define secclass_h #include "firstclass.h" using namespace std; class secclass : public firstclass { private: int *secitem; public: secclass(); secclass(int newitem, int thatitem); ~secclass(); int getsecitem(); void setsecitem(int newitem); }; #endif // implementation of secclass.h // secclass.cpp #include "secclass.h" using namespace std; secclass::secclass() { int *setsecinitial = new int; *setsecinitial = 16; secitem = setsecinitial; } secclass::secclass(int newitem, int thatitem) : firstclass(thatitem) { secitem = &newitem; } secclass::~secclass(){} int secclass::getsecitem() { return *secitem; } void secclass::setsecitem(int newitem) { secitem = &newitem; } // main program #include <iostream> #include "firstclass.h" #include "secclass.h" using namespace std; int main() { firstclass classa; cout << "classa item: " << classa.getitem() << endl << endl; firstclass classz(86); cout << "classz item: " << classz.getitem() << endl << endl; secclass classb; cout << "classb first item: " << classb.getitem() << endl; cout << "classb second item: " << classb.getsecitem() << endl << endl; secclass classc(72, 210); cout << "classc first item: " << classc.getitem() << endl; cout << "classc second item: " << classc.getsecitem() << endl; return 0; }
your constructor
void firstclass::setitem(int thatitem) { item = &thatitem; }
is doing bad thing, storing address of temporary object (the int
passed constructor).
that int
destroyed right after returning constructor , item
pointer pointing memory area has been reused else.
anything can happen when kind of things (including daemons flying out of nostrils) don't that.
Comments
Post a Comment