Getter & Setter , this Keyword in C++ Programming


The getter function is used to retrieve the variable value and the setter function is used to set the variable value. They this is a keyword that refers to the current instance of the class. They are getters and setters the standard way to provide access to data in Java classes. Setters and Getters allow for an object to contain private variables which can be accessed and changed with restrictions.

This is a C++ program that defines a class called student with two private member variables name and age. The class has two constructor parameters to set the values of these variables, a getter and a setter method for each variable, and a method printDetails to print the details of the student object.

In the main function, an object of student class is created using the constructor with the name and age values passed as parameters. The printDetails method is called on the object to print its details. Then, the setName method is called to set the name of the student to "Raj Kumar", and printDetails is called again to print the updated details. Finally, the getName method is called to get the name of the student and print it.

Source Code

#include<iostream>
using namespace std;
class student
{
private:
    string name;
    int age;
public:
    student(string n,int a)
    {
        this->setName(n);
         this->setAge(a);
    }
 
    string getName()
    {
        return this->name;
    }
    void setName(string n)
    {
        this->name=n;
    }
 int getAge()
    {
        return this->age;
    }
    void setAge(int a)
    {
        this->age=a;
    }
    void printDetails()
    {
        cout<<"Name : "<<name<<endl;
        cout<<"Age  : "<<age<<endl;
    }
};
 
int main()
{
    student o("Ram Kumar",25);
    o.printDetails();
    o.setName("Raj Kumar");
     o.printDetails();
     cout<<o.getName()<<endl;
    return 0;
}
 

Output

Name : Ram Kumar
Age  : 25
Name : Raj Kumar
Age  : 25
Raj Kumar
To download raw file Click Here

Program List


Flow Control

IF Statement Examples


Switch Case


Goto Statement


Break and Continue


While Loop


Do While Loop


For Loop


Friend Function in C++


String Examples


Array Examples


Structure Examples


Structure & Pointer Examples


Structure & Functions Examples


Enumeration Examples


Template Examples


Functions


Inheritance Examples

Hierarchical Inheritance


Hybrid Inheritance


Multilevel Inheritance


Multiple Inheritance


Single Level Inheritance


Class and Objects

Constructor Example


Destructor Example


Operator Overloading Example


Operator and Function Example


List of Programs


Pointer Examples


Memory Management Examples


Pointers and Arrays


Virtual Function Examples