Reputation: 465
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;
}
Upvotes: 1
Views: 85
Reputation: 206577
The main problem is that after the function set
returns, student1
points to a dangling pointer. Inside the function, rightStudent
points to the address of name
. That address is invalid once the function returns. Hence, you are seeing undefined behavior.
The program is very brittle. You are storing a pointer but there isn't enough logic to make sure that the pointer remains valid as long as the object (of type student
) is alive.
To make things simple, you should store an object instead of a pointer in student
.
class student
{
public:
void setName(string const& nameVariable);
void printName(){ cout << name; }
private:
string name;
};
Once you change that, the rest of your program becomes simpler.
void student::setName(string const& nameVariable)
{
name = nameVariable;
}
void set(student& student1);
int main()
{
string name = "Nick";
student student1;
student1.setName(name);
student1.printName();
set(student1);
student1.printName();
cout << endl;
system("pause");
}
void set(student& rightStudent)
{
string name = "Jorge";
rightStudent.setName(name);
}
Upvotes: 1