“Setter” and “Getter” Member Functions

Encapsulation is a fundamental principle in object orientation. Encapsulation restricts direct access to a data member of a class. Instead, users query the object itself in order to get or set its members’ values. This is usually done by defining “getter” and “setter” member functions, which are also known as mutators and accessors, respectively. A “plain vanilla” setter returns void and takes one argument?the value to be assigned to an object’s member. Setters and Getters are declared public. Consider the following class:

 class Employee{ int id;//..};

As setter of this class looks as follows:

 class Employee{public: void set_id(int n) {id=n;}};

A classic getter returns a value and takes no arguments; it’s declared as a const member function to document the fact that it only observes an object’s state but doesn’t change it. For example:

 class Employee{public: int get_id() const { return id;}};

Usually, the implementation of setters and getters is trivial: they assign and return a value, respectively. Therefore, they are ideal candidates for inlining. Note however that because they are often defined inside the class body, the inline specifier is redundant, unless you can move the definition outside the class body.

Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

The Latest

microsoft careers

Top Careers at Microsoft

Microsoft has gained its position as one of the top companies in the world, and Microsoft careers are flourishing. This multinational company is efficiently developing popular software and computers with other consumer electronics. It is a dream come true for so many people to acquire a high paid, high-prestige job

your company's audio

4 Areas of Your Company Where Your Audio Really Matters

Your company probably relies on audio more than you realize. Whether you’re creating a spoken text message to a colleague or giving a speech, you want your audio to shine. Otherwise, you could cause avoidable friction points and potentially hurt your brand reputation. For example, let’s say you create a

chrome os developer mode

How to Turn on Chrome OS Developer Mode

Google’s Chrome OS is a popular operating system that is widely used on Chromebooks and other devices. While it is designed to be simple and user-friendly, there are times when users may want to access additional features and functionality. One way to do this is by turning on Chrome OS