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.
#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; }
Name : Ram Kumar Age : 25 Name : Raj Kumar Age : 25 Raj KumarTo download raw file Click Here
Learn All in Tamil © Designed & Developed By Tutor Joes | Privacy Policy | Terms & Conditions