Introduction
Before we proceed with understanding as to how to create a class in c++, we need to first understand the what is a class.
Definition : A class is a container of related data and methods (functions).
Example:
StudentDetails Class |
Data Members : StudentName , StudentAge , StudentAddress |
Methods : GetStudentData , SetStudentData |
The above example shows a simple example as how we can group details of the students and the methods that will be used to access them.
Syntax for creating a class:
class name
{
Access Modifier:
Data members;
Access Modifier:
Methods;
};
Access Modifiers can be:
private | Visible only inside the class. |
protected | Visible inside the class as well as derived (inherited) class. |
public | Visible to every one. |
Note : Normally data members will be either private or protected and methods will be public.
Example:
class StudentDetails{
private:
int studentAge;
char studentName[20];
char studentAddress[50];
public :
void SetStudentData(){
//you can write the logic for setting the data
};
void GetStudentData(){
//you can write the logic for displaying the student data
}
};