Click here to Skip to main content
14,599,201 members
Rate this:
Please Sign up or sign in to vote.
See more:
Function that returns a value of local variable is also called getter?


What I have tried:

Function that returns a value of local variable is also called getter?
Posted
Updated 30-Jun-20 3:12am
Rate this:
Please Sign up or sign in to vote.

Solution 2

You could ... but getters and setters are terms specifically used in pairs to allow encapsulation of your variables within a class.

Unlike C#, C++ doesn't support properties directly, so the name prefixes "get" and "set" are conventionally used to help the reader understand what is going on.
class Employee 
    {
    private:
       int salary;

    public:
        void setSalary(int s) { salary = s; }
        int getSalary() { return salary; }
    }
...
myEmployee.setSalary(56000);
int x = myEmployee.getSalary();
In C# it's a little more elegant, and you use the property as if it was a variable instead of calling functions directly:
class Employee 
    {
    private int salary;
    
    public int Salary 
        {
        get { return salary; }
        set {salary = value; }
        }
    };
...
myEmployee.Salary = 56000;
int x = myEmployee.Salary;
Or even:
class Employee 
    {
    public int Salary { get; set; }
    };
...
myEmployee.Salary = 56000;
int x = myEmployee.Salary;
And the backing variable will be handled automatically.
   
Rate this:
Please Sign up or sign in to vote.

Solution 1

It can be called anything you want. But if you want to know what a getter is then either read your study notes, or Google for "getters and setters".
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100