I'm learning C and I want to know if there is a way you can use variables defined in a class's constructor in a member function. I've tried looking online and in my textbook but I can't find a definitive answer. For example:
class Item {
public:
Item(std::string str) {
std::string text = str;
int pos = -1;
}
void increment() {
// how would I reference pos here?
pos ;
}
};
Thanks in advance!
CodePudding user response:
I want to know if there is a way you can use variables defined in a class's constructor in a member function.
No, you can't. Variables defined in the constructor goes out of scope at the end of the constructor.
The normal way is to initialize member variables in the constructor. These can then be accessed in the member functions:
class Item {
public:
Item(std::string str) : // colon starts the member initializer list
text(std::move(str)),
pos{-1}
{
// empty constructor body
}
void increment() {
pos ; // now you can access `pos`
}
private:
// member variables
std::string text;
int pos;
};
CodePudding user response:
You need to turn text
and pos
into private data members of the Item
class.
Private because, if declared public, they could be easily overwritten making, for instance, redundant the increment()
function, which is an undesirable side effect.
class Item {
public:
Item(std::string str): text{str}, pos{-1} {}
void increment() {
pos ;
}
/* text and pos are now private data members, hence need 'get' functions
in order to access their current value */
std::string& getText() {
return text;
}
int getPos() {
return pos;
}
private:
// text and pos made private members
std::string text;
int pos;
};