Can anyone explan the main idea of using set and get function , because im confusing between them .:-/

class Example {
  int x;
};

Example::x is a private data member. This means that only friends and the Example class itself can access it. This is good practice, data members should be private. But let's say you still want to give users of the class restricted access. A get member function will return the value of x. A set member function will accept a new value for x:

class Example {
  int x;
public:
  int getx() const { return x; }
  void setx ( int value ) { x = value; }
};

This is still unrestricted access, so it's no better than making x public in this particular example. However, unlike making x public, you now have a specific interface that allows for adding restrictions without altering the calling code. Say you want to limit the value of x to a set range. With a public x it can't be done cleanly, but with the get and set member functions it's simple:

class Example {
  int min, max;
  int x;
public:
  Example ( int min, int max )
    : min ( min ), max ( max )
  {}

  int getx() const { return x; }
  void setx ( int value )
  {
    if ( value >= min && value <= max )
      x = value;
  }
};

The concept is simple, though the logic behind it might not make sense if you don't think in terms of public interface vs. private data.

Edited 6 Years Ago by Narue: n/a

I can only advise you to use setters and getters. It gives an overall more stability, atleast you will feel like it when you are programming within your own frameworks. It's hard to explain, but I'm sure you'll one day find out :D
And then it would be good if you are prepared and already have them implemented, instead of having to change a lot of code to have it. Well :)

int getx() const { return x; }

Hey Narue :), I'm just wondering, what difference does your example there have to this, without const?

int getx(){ return x; }

What happens when those brainless getters and setter, need to serve some purpose later one the code, or when the maintainer needs to change some code, or if the programmer makes some mistakes?

I agree! :P

Come on kids... You read in some book that that you MUST use getters and setters and suddenly you all jump on the band wagon.

Hell I'd even argue against the need for object orientated design. The exact same model can be achieved via functional programming.

I've never read that in a book, honestly, I don't have any consideral C++ books. But setters and getters works for me, and since I mostly make libraries used by others, it's the effects of setters and getters are highly useful!

Come on kids... You read in some book that that you MUST use getters and setters and suddenly you all jump on the band wagon.

Hell I'd even argue against the need for object orientated design. The exact same model can be achieved via functional programming.

Lets not go off track. I would love to argue if you posted this in the
geek's forum, but OP's question has been answered, so lets not elongate this thread.

Just make everything public then you don't need to!

Please reread Narue's response -- carefully -- and you will see why this is a bad suggestion.

Some would argue that get and set methods themselves are a symptom of bad design, but even in those situations, they are still superior than providing direct access to a private member variable because they at least do you the service of preventing someone from obtaining a pointer-to your class' local data - something which is nearly always a bad thing.

As others mention, there's also the scenario where a simple set/get combination cease to be simple if perhaps constraints are added to the data (maybe an exception needs to be thrown if the data is invalid?), or perhaps the storage of that data is exported off to some other part of the program and it ceases to be a data member.

The reason we employ design idioms often isn't to add flexibility to a program - quite the opposite, its to add strict constraints to stop other programmers from breaking our code, by forcing the compiler to kick up an error when some other bit of code does something dumb.

IMO, The worst kind of code is usually that which has been designed with the sole intention of saving keystrokes.

Comments
riiiiiiiiiiiiight

Hey Narue :), I'm just wondering, what difference does your example there have to this, without const?

int getx(){ return x; }

Without const you could change x, for example std::swap(a.getX(), a.getY()).

>what difference does your example there have to this, without const?
Without a const qualifier on the member function, you can't call it using const objects:

Example a;
const Example b;

a.getx(); // Okay
b.getx(); // Bzzt! Can't call non-const member function on const object

With the const qualifier, you can call the member function on both const and non-const objects. It's recommended to add the const qualifier to any member functions that don't modify an object's state.

>Without const you could change x, for example std::swap(a.getX(), a.getY()).
Um..no. Either way the return value is not const, and modifiable. However, it's not a reference into the object, so you'd only be modifying a copy of the value. Note that const in this case is applied to the member function, not the value.

I have no idea why I would make a const object, but I'll take your advice and start making member functions

that don't modify an object's state

constants :)

Thanks!

>>>>I have no idea why I would make a const object

1) For good programming habbits
2) When you create an object thats const, you could only use the const
corrected public interface. Take a look

#include<iostream>
#include<string>

using namespace std;


class A
{
private:
	int var;
public:
	A() : var(0){}
	A(int i) : var(i){}
	int getVar_noConst(){ return var; }
	int getVar_Const()const{ return var;}
};

int main()
{	 
	A nonConstObj(10);
	//nonConstObj could use all public interface
	int j = nonConstObj.getVar_Const();
	int k = nonConstObj.getVar_noConst();

	
	const A constObj(-10);
	//while constObj can only uses const corrected function
	int l = constObj.getVar_Const();
	//int m = constObj.getVar_noConst(); ERROR
	
	return 0;
}

Or let's say you don't create an object that is itself const.

int main()
{
   T t(42);
   display(t);
   return 0;
}

But we have this display() function. It has no business changing anything in the object, it just displays stuff. Since it doesn't change the object, we make sure the caller (and the compiler) is aware of this feature we are providing, and pass by const reference.

void display(const T &t)
{
   std::cout << "The object contains the following data:\n";
   t.print();
}

We can't call the member function print() unless it is const because we have passed t to display() as a const reference.

#include <iostream>

class T
{
   int data;
public:
   T(int data_ = 0)
   : data(data_)
   {
   }
   void print() const
   {
      std::cout << data << "\n";
   }
};

void display(const T &t)
{
   std::cout << "The object contains the following data:\n";
   t.print();
}

int main()
{
   T t(42);
   display(t);
   return 0;
}

/* my output
The object contains the following data:
42
*/

This is a bit of a canned example, but this sort of thing with the function signature might be a little bit more of a common way to run into the const issue.

This article has been dead for over six months. Start a new discussion instead.