February 29, 2012

Getter Setter Example Code in C++

#include <cstdlib>
#include <iostream>

using namespace std;

// defining the Student class
class Student
{
string Name, Rollnumber, Semester, CGPA;

public:

//Default Constructor of the class
Student::Student()
{
Name = “Default Name”;
Rollnumber = “Default Roll Number”;
Semester = “Default Semester”;
CGPA = “Default CGPA”;
cout << “:: Student Class :: \n” << endl;
}

void setName (string);
void setRollnumber (string);
void setSemester (string);
void setCGPA (string);

string getName ();
string getRollnumber ();
string getSemester ();
string getCGPA ();

void Display();
};

// setting the value of Name
void Student::setName (string inputData)
{
Name = inputData;
}

// setting the value of Rollnumber
void Student::setRollnumber (string inputData)
{
Rollnumber = inputData;
}

// setting the value of Semester
void Student::setSemester (string inputData)
{
Semester = inputData;
}

// setting the value of CGPA
void Student::setCGPA (string inputData)
{
CGPA = inputData;
}

// getting the value of Name
string Student::getName ()
{
return Name;
}

// getting the value of Rollnumber
string Student::getRollnumber ()
{
return Rollnumber;
}

// getting the value of Semester
string Student::getSemester ()
{
return Semester;
}

// getting the value of CGPA
string Student::getCGPA ()
{
return CGPA;
}

void Student::Display ()
{
cout << ” Name: ” << getName() << “\n Roll Number: ” << getRollnumber() <<  “\n Semester: ” << getSemester() <<  “\n CGPA: ” << getCGPA() << “\n \n”;
}

int main(int argc, char *argv[])
{

Student studentInfo;   // creating object of Student class

//Setting student information

studentInfo.setName(“Fahad Mahmood”);
studentInfo.setRollnumber(“mc100200752”);
studentInfo.setSemester(“1st, Spring 2010”);
studentInfo.setCGPA(“Awaiting criteria…”);

//Displaying information with the function Display

studentInfo.Display();

system(“PAUSE”);
return EXIT_SUCCESS;
}

Last updated: March 19, 2014