Nick Tsui
Nick Tsui

Reputation: 634

Setting private properties of a class using its public methods, c++

Something like this:

class someclass
{
public:
    someclass();
    ~someclass();

    long   Set(int x, int y);

private:
        int _x;
        int _y;
};

long   Set(int x, int y)
{
   _x = x;
   _y = y;
}

But if you just write something like this, the _x cannot be recognized inside Set() function. So how do I setting the private properties of a class using its own methods? Thanks a lot.

Upvotes: 1

Views: 156

Answers (3)

John Dibling
John Dibling

Reputation: 101476

You have what is effectively a typo. You have declared one member function:

class someclass
{
public:
    long   Set(int x, int y);

...but implemented a completely different, free function:

long   Set(int x, int y)
{
   _x = x;
   _y = y;
}

Change the latter to:

long   someclass:Set(int x, int y)
{
   _x = x;
   _y = y;
}

Upvotes: 3

When you define a member function outside of its class definition, you have to scope it appropriately:

long someClass::Set(int x, int y)
{
  _x = x;
 _y = y;
}

What you wrote defined an unrelated global function Set.

Also, the return type of Set should probably be void (or you must return something from it).

Upvotes: 4

Rody Oldenhuis
Rody Oldenhuis

Reputation: 38042

You have a scoping problem there. This should work:

long someclass::Set(int x, int y)
{
   _x = x;
   _y = y;
}

Upvotes: 6

Related Questions