I am having trouble accessing and setting data from inside classes.
if have a program set up similar to this example
Then the pen class looks like
from the main function i have
This code works but if i send *myDesk to another class and try to use it like
string s = myDesk->getPen()->getPenName() line crashes the program
how can i do this correctly?
Thank you,
if have a program set up similar to this example
Code:
---Desk.h---- #include "Pen.h" class Desk { private: Pen myPen; public: Desk(); void setPen(Pen*); Pen* getPen(); } ---Desk.cpp----- Desk::Desk(){} Pen* Desk::getPen() { return &myPen; } void setPen(Pen* p) { myPen = p }
Code:
---Pen.h--- #include <string> class Pen { private: string penName; public: Pen(); string getPenName(); void setPenName(string); } --Pen.cpp--- include "Pen.cpp" Pen::Pen(){ penName = "Bic"; } string Pen::getPenName() { return penName() } void Pen::setPenName(string s) { penName = s }
Code:
Desk myDesk; cout << myDesk.getPen()->getPenName();
Code:
--Main.cpp--- ... myOtherClass.setDesk(&myDesk); ... ---OtherClass.h--- ... Desk* myDesk; ... ---OtherClass.cpp--- ... void randomFunction(){ string s = myDesk->getPen()->getPenName() ...
how can i do this correctly?
Thank you,
Comment