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
Click For Summary

Discussion Overview

The discussion revolves around how to initialize or set the values of private members in a class using client code, specifically focusing on different programming languages, including Java and C++.

Discussion Character

  • Technical explanation

Main Points Raised

  • One participant, Jim, inquires about initializing private members of a class from client code.
  • Another participant suggests using setter methods as a solution, providing a Java example of a class with private members and corresponding getter and setter methods.
  • A later participant, Hurkyl, asks for guidance on how to achieve similar functionality in C++, specifically how to initialize or change private member variables in the main function.
  • A subsequent reply provides a C++ code snippet demonstrating the use of a setter method to set a private variable and retrieve its value.

Areas of Agreement / Disagreement

Participants generally agree on the use of setter methods as a means to access and modify private members, but there is a lack of consensus on the specific implementation details across different programming languages.

Contextual Notes

The discussion does not address potential limitations or assumptions regarding the use of setter methods in different contexts or languages.

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   Reactions: 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;
}
 

Similar threads

Replies
7
Views
3K
Replies
16
Views
3K
  • · Replies 6 ·
Replies
6
Views
3K
  • · Replies 34 ·
2
Replies
34
Views
4K
  • · Replies 2 ·
Replies
2
Views
2K
Replies
18
Views
9K
  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 1 ·
Replies
1
Views
4K
  • · Replies 5 ·
Replies
5
Views
3K
  • · Replies 39 ·
2
Replies
39
Views
8K