+ 1

Another code problems

#include <iostream> #include <vector> using namespace std; //number you inputed class Number{ public: int setNumber(){ cin >> num; } int getNumber(){ return num; } friend void infoStreamerN(Number *obj); protected: int num; }; //number in cube class CubeNumber : public Number{ public: int getCubeNumber (){ return cNum; } friend void infoStreamerCn(CubeNumber *obj1); private: int cNum = num*num*num; }; //outputs information void infoStreamer(Number *obj){ cout << "Your input: " << obj->getNumber() << "\n"; delete obj; } void infoStreamerCn(CubeNumber *obj1){ cout << obj1->getNumber() << "^3 = " << obj1->getCubeNumber(); } int main() { Number *n = new Number; CubeNumber *cn = new CubeNumber; n->setNumber(); infoStreamer(n); infoStreamerCn(cn); return 0; } Outputs 63838282 but it isn't an inputed number. Am i overloading memory somewhere or pointing into wrong space? Write your answers.

18th Aug 2018, 6:31 AM
Oleg Storm
Oleg Storm - avatar
4 Antworten
+ 1
Oh, didn't know that, thanks😄
18th Aug 2018, 7:12 AM
Oleg Storm
Oleg Storm - avatar
+ 1
changes I have done are as below : 1. one object of base class pointing to derived class 2. type cast Number* to CubeNumber* while calling infostreamerCn 3. setCubenumber added and avoided direct value assignment to private member 4. call method setCubenumber from infostreamerCn 5. most important is don't delete obj from infostreamer...so, commented that line
18th Aug 2018, 7:20 AM
Ketan Lalcheta
Ketan Lalcheta - avatar
0
Oleg Storm this is expected output... nothing wrong is there in output... why ? because you have created two different objects... one for each derived class and base class... so, once you go to CubeNumber method, it finds getnumber method due to inheritance , but value is returned by that object's value.. You set input value to Number object, not CubeNumber..
18th Aug 2018, 7:10 AM
Ketan Lalcheta
Ketan Lalcheta - avatar
0
Oleg Storm , If you wish, it should be like below : #include <iostream> #include <vector> using namespace std; //number you inputed class Number{ public: int setNumber(){ cin >> num; } int getNumber(){ return num; } friend void infoStreamerN(Number *obj); protected: int num; }; //number in cube class CubeNumber : public Number{ public: int getCubeNumber (){ return cNum; } void setCubeNumber (){ cNum = num*num*num; } friend void infoStreamerCn(CubeNumber *obj1); private: int cNum; }; //outputs information void infoStreamer(Number *obj){ cout << "Your input: " << obj->getNumber() << "\n"; //delete obj; } void infoStreamerCn(CubeNumber *obj1){ obj1 -> setCubeNumber(); cout << obj1->getNumber() << "^3 = " << obj1->getCubeNumber(); } int main() { Number *n = new CubeNumber; n->setNumber(); infoStreamer(n); infoStreamerCn((CubeNumber*)n); return 0; }
18th Aug 2018, 7:16 AM
Ketan Lalcheta
Ketan Lalcheta - avatar