Ja Jang Myeon
Ja Jang Myeon

Reputation: 41

Using a method within a class as an operator to assign a value to private member of the class

Folks, I am trying to use a method within a class to assign a value to a private member of that class. I can't figure this out to save my hind-parts. Can anyone please point out the obvious?

#include <cstdlib>
#include <cstdio>
using namespace std;
class NoClass {
    public:
        NoClass() { };
        NoClass(const NoClass& orig) { };
        virtual ~NoClass() { };
        void SetAnInt() {
            this->anInt = ???;
        }
        int GetAnInt() {
            return this->anInt;
        }
    private:
        int anInt;
};


int main(int argc, char** argv) {
    NoClass *nc = new NoClass();
    nc->SetAnInt() = 133; // Important part here
    printf("%d\n", nc->GetAnInt());
    return 0;
}

Upvotes: 2

Views: 111

Answers (2)

gchen
gchen

Reputation: 1173

You can pass in the value that you want to set to as a argument.

void SetAnInt(int val) {
    this->anInt = val;
     //or just
    //anInt = val
    }

Then, you can call it in main like

 nc->SetAnInt(133);

Alternatively, to be able to write

nc->SetAnInt() = 133; 

you will need to make SetAnInt() return a reference to the data member anInt

int& SetAnInt() {
    return anInt;
}

Upvotes: 2

3Dave
3Dave

Reputation: 29081

Just for fun, you can do this:

#include <cstdlib>
#include <cstdio>
using namespace std;
class NoClass {
    public:
        NoClass() { };
        NoClass(const NoClass& orig) { };
        virtual ~NoClass() { };

        int& SetAnInt() {
            return anInt;
        }

        int GetAnInt() {
            return this->anInt;
        }
    private:
        int anInt;
};


int main(int argc, char** argv) {
    NoClass *nc = new NoClass();
    nc->SetAnInt() = 133; // Important part here
    printf("%d\n", nc->GetAnInt());
    return 0;
}

Note that this exploits the language to overcome data hiding, which is one of the cornerstones of object-oriented programming. It's bad. Like, really, really bad. So, don't do it. But, you can. And I'd love to hear what your professor says about it.

Also, extraneous this-> harms code readability, and this isn't java.

Upvotes: 3

Related Questions