getters/setters

Getters and setters are the common names for what is more formally known as the Accessors and Mutators, respectively, which provide the methods to set and get values for an object.

 

Since we want to keep all data private to the object, we need specific methods defined to allow an object to control how its data is accessed.

 

The general approach is to prefix the method names with set / get as per their required functionality:

e.g.

setHeight()... //to set the height attribute

getHeight()... //to get the height attribute

 

Since the scope of data members is local to the class (i.e. within its curly braces {}), values can be assigned to them by passing in a parameter to a class's method specifically defined for this purpose. Assuming a float height ; private member has been declared, we can set its value as follows:

 

void setHeight(float myVar) {

height = myVar ;

}

 

As we are simply setting a value and expect no return, we use the void data type for the method. It is then followed by the setHeight identifier for the method and the expected parameter data type and identifier to be used within the body. The function then simply assigns the passed in myVar variable to the previously declared private member variable height.

 

Similarly, to get a value, a method is defined that simply returns the desired value:

 

float getHeight(){

return height ;

}

 

The data type of the expected return value is declared for the getter, which is then followed by the getHeight identifier for the method whose body simply returns that value.

 

Continuing with the previous examples, we have already seen the getter and setter methods being used:

Compile & Run:

myTriangle width was set at 12
myTriangle height was set at 2000
myTriangle area: 12000

Leave a Reply