How can I initialize private members in a class using client code?

  • Thread starter Thread starter Jim Roberts
  • Start date Start date
  • Tags Tags
    Members
AI Thread Summary
To initialize or set the values of private members in a class from client code, setter methods are commonly used. In Java, this is demonstrated with a class that includes private variables and public getter and setter methods. For C++, the same concept applies. A class can be defined with private member variables, and public methods can be created to modify and access these variables. In the provided C++ example, an instance of the class is created in the main function, and the setter method is used to assign a value to the private member, which can then be retrieved using the getter method. This approach maintains encapsulation while allowing controlled access to private data.
Jim Roberts
Messages
3
Reaction score
0
I have a class and i'd like to initialize
or set the values of its private members
in the client code, how can I do that ?
thanku,

jim
 
Computer science news on Phys.org
Through setter methods.

For example, in Java style:

Code:
public class Example {
  private int var;

  public int getVar() { return var; }
  public void setVar(int i) { var = i; }
}
 
  • Like
Likes WWGD
:wink:, but can you tell me how to do that in c++?
and initialize/change the values of class's private
member variables in main function ?
thanks hurkyl
 
Code:
int main(int argc, char *argv[]) {
Example exmpl;

exmpl.setVar(2004);
printf("private var = %d\n", exmpl.getVar());

return 0;
}
 
In my discussions elsewhere, I've noticed a lot of disagreement regarding AI. A question that comes up is, "Is AI hype?" Unfortunately, when this question is asked, the one asking, as far as I can tell, may mean one of three things which can lead to lots of confusion. I'll list them out now for clarity. 1. Can AI do everything a human can do and how close are we to that? 2. Are corporations and governments using the promise of AI to gain more power for themselves? 3. Are AI and transhumans...
Sorry if 'Profile Badge' is not the correct term. I have an MS 365 subscription and I've noticed on my Word documents the small circle with my initials in it is sometimes different in colour document to document (it's the circle at the top right of the doc, that, when you hover over it it tells you you're signed in; if you click on it you get a bit more info). Last night I had four docs with a red circle, one with blue. When I closed the blue and opened it again it was red. Today I have 3...
Back
Top