Class
Class is a user defined data structure, it contains both data and functions. Lets take an example:
int x; // 5;
class student; // Saad, 101
In first case int is used because we only want to save an integer value but if we want to store a data consisting of more than one type like in case of a student which includes its name,roll number etc, then we will define our own data type i.e student. Below mentioned example gives a complete overview of a user defined data structure (Class).
Example
#include "stdafx.h"
#include "iostream"
#include "conio.h"
#include "string"
using namespace std;
// STUDENT CLASS, A STUDENT IS DEFINED IN TERMS
// OF ITS ATTRIBUTES I.E NAME, ROLL NUMBER ETC
class student
{
// ATTRIBUTES OF A STUDENT, THESE ARE DECLARED AS PRIVATE
private:
string name;
int rollNo;
// ALL FUNCTIONS OF A STUDENT CLASS
public:
student();
student(string,int);
void setName(string);
void setRollNo(int);
string getName();
int getRollNo();
void display();
};
// CONSTRUCTOR 1
student::student()
{
}
// CONSTRUCTOR 2
student::student(string _name, int _rollNo)
{
setName(_name);
setRollNo(_rollNo);
}
// FUNCTION FOR SETTING THE NAME OF THE STUDENT
void student::setName(string _name)
{
name = _name ;
}
// FUNCTION FOR SETTING THE ROLL NUMBER OF THE STUDENT
void student::setRollNo(int _rollNo)
{
if ( _rollNo > 0 )
rollNo = _rollNo ;
}
// FUNCTION FOR RETURNING THE NAME OF THE STUDENT
string student::getName()
{
return name;
}
// FUNCTION FOR RETURNING THE ROLL NUMBER OF THE STUDENT
int student::getRollNo()
{
return rollNo;
}
// FUNCTION FOR DISPLAYING THE ATTRIBUTES OF A PARTICULAR STUDENT
void student::display()
{
cout << "Student name : " << getName() << endl;
cout << "Student roll # : " << getRollNo() <<endl ;
}
// DRIVER PROGRAM
int main()
{
student S1("Saad Bin Saulat",101);
S1.display();
student S2("Osama Shaukat",102);
S2.display();
student S3("Ayesha Khan",103);
S3.display();
_getche();
return 0;
}
Output
Student name : Saad Bin Saulat
Student roll # : 101
Student name : Osama Shaukat
Student roll # : 102
Student name : Ayesha Khan
Student roll # : 103
0 comments:
Post a Comment