Can someone please explain these functions when creating a class please. Searching hasn't helped much. I need to know how they are used and examples or links to examples would be helpful. Any help is appreciated.

Can someone please explain these functions when creating a class please. Searching hasn't helped much. I need to know how they are used and examples or links to examples would be helpful. Any help is appreciated.

"Get & Set" are kind of informal terms used to describe functions that allow users of the class to access the class's private member variables for reading (Get) and writing (Set). Typically, you'd have something like this:

class MyClass{
    public:
        const int Get() const{    return m_variable;       }
        void Set( int newValue ){  m_variable = newValue;   }

    private:
        int m_variable;
};

If you wanted, you could have a Get and a Set for each member variable. Maybe there are some member variables that the user doesn't need access to though (they might be used internally in the class as counters or something).

This might look like a lot of work when you could just make the member variable public and set it directly. However, this way you have more control. For example, maybe you want m_variable to only be in the range 0 - 10, in which case, you'd just change the Set function to check the number you give it before setting the variable:

void MyClass::Set( int newNumber ){
    if ( newNumber < 10 ){
        m_variable = ( newNumber > 0 ? newNumber : 0 );
    }
    else{
        m_variable = 10;
    }
}

There's also some things about encapsulation, which may not mean much to you at the moment. Basically, you want to keep the actual data in the class (i.e. the member variables) as restricted as possible, but have nice functions for getting at it. This helps if you decide to reorganize the internals of the class because you can just change the way the functions are implemented, but users of the class needn't know that anything has happened at all.

So, say I have a class that stores lists of numbers and has a function that gives you the average of the numbers, we'll call it ave() . I might have originally thought that it was going to be a good idea to store all the numbers and have another variable that held the average. Then, when the user calls ave() just return the value of that variable (like the Get() function above). One day, I might decide that this is a terrible way to implement my class and that I should get rid of the variable that stores the average and just calculate the average from scratch every time the ave() function is called. If everything's properly encapsulated, then the user will not notice any difference, they won't have to change any of their code at all. All the places where they call ave() will still get the average that they're expecting. If You'd just exposed the member variable, then they'd be in all kinds of trouble when you suddenly decided to get rid of it because all their code that uses the class will have to be altered. Not good.

I hope that all makes some sense! :o)

These functions stem from the guideline that data members should be kept private to avoid losing control over your data. For example:

#include <iostream>
#include <string>

class CellPhone {
public:
    std::string number;
    
    CellPhone(const std::string& number): number(number) {}
};

int main()
{
    CellPhone myPhone("555-123-4567");

    std::cout<< myPhone.number <<'\n';
    myPhone.number = "Haha, this isn't a phone number";
    std::cout<< myPhone.number <<'\n';
}

All hell can break loose when you expose a class' state for any use, so the usual advice is to make such data members private:

class CellPhone {
private:
    std::string number;
public:    
    CellPhone(const std::string& number): number(number) {}
};

Now the issue becomes accessing the data at all. In making number private, it becomes completely inaccessible to the outside, which may not be what's wanted. Perhaps we want the outside world to see it but not change it. This could be a use for a getter:

class CellPhone {
private:
    std::string number;
public:    
    CellPhone(const std::string& number): number(number) {}

    std::string Number() const { return number; }
};

int main()
{
    CellPhone myPhone("555-123-4567");

    std::cout<< myPhone.Number() <<'\n';
}

The data member is exposed, but read-only. You might also want to support modification, but still want to maintain enough control to avoid chaos. For example, validating the new phone number. This is the purpose of a setter:

class CellPhone {
private:
    std::string number;
public:    
    CellPhone(const std::string& number): number(number) {}

    std::string Number() const { return number; }

    void Number(const std::string& newNumber)
    {
        if (!ValidPhoneNumber(newNumber))
            throw std::invalid_argument("Invalid phone number");

        number = newNumber;
    }
};

int main()
{
    CellPhone myPhone("555-123-4567");

    std::cout<< myPhone.Number() <<'\n';

    try {
        myPhone.Number("Haha, this isn't a phone number");
    } catch (const std::invalid_argument& ex) {
        std::cerr<< ex.what() <<'\n';
    }

    std::cout<< myPhone.Number() <<'\n';
}

It's all about controlled access to an object's state.

commented: Great use of examples +0
commented: Excellent post +3

Well I thought they were preset functions in a library. So set is for inputting into the member from either the user or set by the programmer and the get is to input it to the user??

Thanks for the info. I understand most of it now though

As said, the setter functions are intended to modify class member variables in a specific instance of an object of the class. Conversely, getter functions are intended to access the values of those data members. This allows you to specify that the data members are private, keeping outside code from modifying those values without knowing any limitations that the class code may enforce upon the data, such as range checking for numeric values and such. As Narue indicated, allowing others to modify data members of your class directly could easily be a "bad thing".

Typically it works like this:

class Account
{
private:
  double m_LastDepositTime; // Julian date+time value
  double m_LastDepositAmt;  // Amount of last deposit

  Account& operator=(const Account&); // Assignment not allowed
public:
  Account() : m_LastDepoitTime(0.0), m_LastDepositAmt(0.0) {}
  ~Account() {}

// Setter function - this could be called makeDeposit(double,double) for better
// readability of code.
  void setLastDeposit( double dateTime, double amount );


// Getter functions
  double getLastDepositAmt() const { return m_LastDepositAmt; }
  double getLastDepositTime() const { return m_LastDepositTime; }
};
commented: very helpful +0

Thanks. Now I think I totally get it. Just to figure out how to assign members now, but that's another thread I guess.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.