Getter and Setter

0 Faha Sharapov · March 16, 2015
Hi Bucky,

First of all wanna thank you for all your hard work on creating this amazing website! All your tutorials are great. I promise, I will share my first pay check (when I get a job as a software developer) with you, buddy! Thanks!

Now, my question is (based on this particular tutorial -13)  -  Isn't it better or simpler to create just a setFunc instead of creating setFunc and the getFunc? Please, see below.

class MyClass {
    public:
    string setFunc (string x)
    {
        author = x;
        return author;
    }

    private:
        string author;

};


int main(){

MyClass obj;
cout << obj.setFunc("Faha Sharapov");

}

.The output will be the same if you use both the "setter" and the "getter".

Post a Reply

Replies

Oldest  Newest  Rating
0 Faha Sharapov · March 16, 2015
I think I am missing the point... Although, on the above code, I am retrieving the value from setFunc, without using the "getFunc"...
Confused...
0 Faha Sharapov · March 16, 2015
"You're retrieving the value after it has been updated, correct. What if you want to retrieve the value without updating it?"  -  Would you please be able to show me in the example?
0 Faha Sharapov · March 16, 2015
Thanks a lot for explaining in details. I really appreciate it.
Gotta say that I have a little knowledge of c++, thus please see the code below. It's not complete and it is really badly written, but the main point is that I "could" (if I can say that) come up with something where I don't use the "getters" (not sure if this method can be used in programming though)... And again, the program is not complete, and it is badly written, but it retrieves the data from "setters" only...

#include <iostream>
#include <string>

using namespace std;


class Student {

private:
string name;
unsigned int grade;


public:
string set_name(string value)
{
    name = value;
    return name;
}

unsigned int set_grade(unsigned int value)
{
    grade = value;
    return grade;
}


};



int main()
{


int student_count;

cout << "Enter the number of students in your class" << endl;
cin >> student_count;


for  (int count = 1; count <= student_count; count ++)
{
    string name;
    unsigned int grade;

    cout << "Enter a student's name" << endl;
    cin >> name;

    cout << "Enter " << name << "'s grade" << endl;
    cin >> grade;

    Student obj1;
    cout << obj1.set_name(name) << endl;

    Student obj2;
    cout << obj2.set_grade(grade) << endl;

}
return 0;
}
0 Faha Sharapov · March 17, 2015
Don't know yet... But let me figure out how...
  • 1

C++

107,107 followers
About

Used in many types of software including music players, video games, and many large scale applications.

Links
Moderators
Bucky Roberts Administrator