Question about structs in class which wouldn't save value.
I have a question about this particular code.
The structs would not save the value entered by the user into its class' attributes.
If you do not understand what i am talking about, please compile the code below. Can someone kindly explain what is the problem and how to fix it? Thank you for your time.
Code:
#include <iostream>
#include <string>
using namespace std;
class Sam
{
struct sample{
int a;
string b;
};
public:
void set_a();
void set_b();
int ret_a();
string ret_b();
};
void Sam::set_a()
{
int a1;
cout<<"Insert int a";
cin>>a1;
sample().a=a1;
}
int Sam::ret_a()
{
return sample().a;
}
void Sam::set_b()
{
string b1;
cout<<"Insert string b";
cin>>b1;
sample().b=b1;
}
string Sam::ret_b()
{
return sample().b;
}
int main()
{
Sam c;
c.set_a();
c.set_b();
cout<<c.ret_a()<<endl<<c.ret_b(); //It should output the same value inputted by the user
// but it shows nonsense. why is it so?
return 0;
}
Re: Question about structs in class which wouldn't save value.
Quote:
Originally Posted by
hayloiuy
Can someone kindly explain what is the problem
What does this line do?
It creates a temporary variable of type "sample". Temporary variables are destroyed as soon as the statement is executed, therefore nothing has happened.
Quote:
and how to fix it?
You create a member variable.
Code:
#include <iostream>
#include <string>
using namespace std;
class Sam
{
struct sample{
int a;
string b;
};
sample mySampleA, mySampleB;
public:
void set_a();
void set_b();
int ret_a();
string ret_b();
};
void Sam::set_a()
{
int a1;
cout<<"Insert int a";
cin>>a1;
mySampleA.a=a1;
}
int Sam::ret_a()
{
return mySampleA.a;
}
Regards,
Paul McKenzie
Re: Question about structs in class which wouldn't save value.
AARGGGHHHH this is just a very very simple mistake which i overlook. I spent 2 hours thinking what is the problem. Imagine that. If there are any thumbs up in this forum i will give you a hundred. Thank you very much and i am very very deeply sorry for wasting your time.
Re: Question about structs in class which wouldn't save value.
Quote:
If there are any thumbs up
There is... :) just add :thumb:
Re: Question about structs in class which wouldn't save value.
Since copying a std::string object might be expensive changing the ret_b() method to
Code:
const std::string& Sam::ret_b() const
{
return b;
}
might be useful, too.