Getter and Setter in C++

Getter and setter are used when we define our own data type which also known as abstract data types. In abstract data types when we declare some functions or variables as private which are not accessible from outside of that class then these function are used to access them. Remember through this we just get the value of those variables and can't change them.

Source Code

#include<iostream>
#include <cstdlib>
using namespace std;
class LEP 
{
 string name;
   int  roll_no;
   public:
   void set_name (string);
   void set_roll_no(int);
   string get_name();
   int get_roll_no();
   void display();
};
void LEP::set_name(string n)
{
 name = n;
}
void LEP::set_roll_no(int r)
{
 roll_no = r;
}
string LEP::get_name()
{
 return name;
}
int LEP::get_roll_no()
{
 return roll_no;
}
void LEP::display ()
{
 cout<<" The Name of the Student is : "<<get_name() ;
 cout<<endl;
 cout<<" The Roll # the Student is :" <<get_roll_no();
 cout<<endl;
}
int main ()
{
 LEP L;
 string name;
 int roll;
 cout<<" Enter Your Name :";
 cin>>name;
 cout<<" Enter Your Roll # :";
 cin>>roll;
 L.set_name(name);
 L.set_roll_no(roll);
 L.display();
 }

Output of the Program

 Getter and Setter in C++

Share on Google Plus

About Asad

Asad Niazi is Software Engineer , Programmer, Web Developer and a young mentor of BloggersTown and PProgramming. Asad Love to writes about Technology, Programming, Blogging and make money online.
    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment