0
What am i doing wrong?
#include <iostream> #include <string> using namespace std; class MyClass { private : string myData ; public : void setMyData(string s) { myData = s; } } ; int main() { MyClass obj; obj.setMyData ("test" ) ; cout << obj; return 0; }
3 Answers
+ 2
I suggest using getters and setters. From what I know they help you prevent errors and help you update components that are dependent on your data. For example if you call your data and you data is null it could potentially throw an error, another example is if you have a variable named "player.position" and you update it, it will also update the player drawable component's position:
void setPosition(Point newPosition) {
position = newPosition;
drawable.position = newPosition;
}
Also here is your code with the getters and setters implemented ;)
#include <iostream>
#include <string>
using namespace std;
class MyClass {
private:
string data;
public:
void setData(string s) {
data = s;
}
string getData() {
return data;
}
} ;
int main() {
MyClass obj;
obj.setData("test");
cout << obj.getData();
return 0;
}
Let me know if you need anything else!
+ 1
Hello, it seems like you want to print obj's data so you need to write "cout << obj.myData;", so to access "myData" on "obj" you also need to declare "myData" in the public section.
+ 1
You can't print MyClass object directly because the compiler doesn't know what to print. A simple way to do is to make another function that returns myData. Or make myData public. And then you can call the function after cout.