Pages

How to create class in C++

Class In C++


     Today i am going to explain you how to create class using c++ programming language. First of all, what is the meaning of Class? why we need classes? Class is a user defined type or data structure declare with keyword class that has DATA and FUNCTIONS(Methods). Class is a kind of structure. We can develop new data types using classes.



      Here is the class called "Student" and several properties in it. After creating this student class, then we can create memory locations according to it. (Ex- student S1 , student S2) Those are called objects in class. In class there are not only properties but also has methods.


     We can call Methods in class like, S1.DisplayDetails() , S2.Calculate(). We need methods to read properties of class.

Create a Class

    I will explain how to create a class using very simple example. Imagine we need to build "student grading system" to a university. In here we should output to the user, student Name , his/her ID and pass/fail according to the GPA. 
     To create a class we need two files, student.h and student.cpp.

Student.h

class student
{
   private:
        int ID;
        char name[20];
        double gpa;

   Public:
        student(int pid, char pname[], double pgpa);
        void getGrade(double value);
        void DisplayDetails();
 };

Private - Outside programmes(main programme) can't read data in private section.

Public - Outside programmes can freely read and change data in public section.

Constructor (student(int pid, char pname[], double pgpa)) - We use constructor to assign values that in main programme to private section data.


student.cpp (detailed one)

#include "student.h"
#include <cstring>
#include <iostream>
using namespace std;

 student::student(int pid, char pname, double pgpa)
{
    ID     =  pid;
    strcpy = (name , pname);
    gpa    =  pgpa;
}

 void student::getGrade(double value)
{
    if(value>=45)
     {
            cout<<"Pass!"<<endl;
     }
    else
     {
            cout<<"Fail!"<<endl;
     }
}

void student::DisplayDetails()
{
   cout<<"ID \t: "<<ID<<endl;
   cout<<"Name \t:"<<name<<endl;
   cout<<"Gpa \t:"<<gpa<<endl;
}

    Now we finish writing our class. Then we should write our main programme.

Main.cpp

#include "student.h"
#include <iostream>

int main()
{
   student s1(1001,"david", 65.0); /*create object call s1 and assign values to it. */

   s1.DisplayDetails(); /*dispaly student information.*/

   cout<<endl;

   s1.getGrade(65.0); /*Display Pass / Fail */

return 0;

}

Dynamic Method (using pointers)



#include "student.h"

#include <iostream>


int main()
{
   student*s1;
   s1 = new student(1001,"david", 65.0); /*create object call s1 and assign values to it. */

   s1->DisplayDetails(); /*dispaly student information.*/

   cout<<endl;

   s1->getGrade(65.0); /*Display Pass / Fail */

return 0;

}



Article By - Nisal Priyanka