How do I pass an object that has a pointer member inside it to a function? I want to be able to modify that objects member and have the original object in main have the modified value reflected upon it, Simple code I just want to know how to do this. I'm new. I made this code as simple as I code, I tried an overloaded assignment operator and a copy constructor but still no good. Can someone explain to me the process that happens when I call the function set(); and why I am getting an error
i want to use the set() function to change the objects name member to a different one
#include <iostream> #include <string> using namespace std; class student { public: void setName(string *nameVariable); void printName(){ cout << *name; } private: string *name; }; void student::setName(string *nameVariable) { name = nameVariable; } void set(student& student1); int main() { string *nameptr, name;//creates pointer and varible of type string nameptr = &name;//sets nameptr to the adress of name *nameptr = "Nick";//inderict access, assigns what nameptr is pointing to the value"nick" student student1; student1.setName(nameptr); student1.printName();//couts - Nick - set(student1); student1.printName();//should cout - Jorge - after modification however an error occurs cout << endl; system("pause"); } void set(student& rightStudent) { string *nameptr, name; nameptr = &name; *nameptr = "Jorge"; student localStudent; localStudent.setName(nameptr); rightStudent = localStudent; }
newunless you have to. As a beginner, you shouldn't have to. Also, read about the "Law of Three", which is essential info about the C++ object model.