Object and Class in C++

In this tutorial, we will learn about the Object and Class in C++, how to write simple class.

A Simple Class

Syntax of class

class student //define a class
{
   private:
      int roll; //class data
   public:
      void setdata(int number) //member function to set data
        { roll = number; }
      void showdata() //member function to display data
        { cout << “Roll number is “ << roll << endl; }
}; // semiclon is must

Here, student is the class name given to the defined class. It contains one data item of type int. and two  member functions. There can be any number of data members in class.  setdata and showdata are the member function and  private  and public are the access specifier we will discuss more about it below.

 

We have placed data and function in a single class / entitiy. It is the one of characteristics of OOP. 

Class in c++
fig: class in C++

Example of class

#include <iostream>
using namespace std;

class student //define a class
{
   private:
      int roll; //class data
   public:
      void setdata(int number) //member function to set data
        { roll = number; }
      void showdata() //member function to display data
        { cout << “Roll number is “ << roll << endl; }
}; // semiclon is must

int main()
{
    student s1, s2; //define two objects of class student
    s1.setdata(22); //call member function to set data
    s2.setdata(33);
    s1.showdata(); //call member function to display data
    s2.showdata();
   return 0;
}

Output

Roll number is 22
Roll number is 33

Defining Objects

In above program inside main 

student s1, s2;

Here, Two objects s1 and s2  are Objects of class student. 

Syntax of Declaring Object

class_name object_name;

In above example,

s1.setdata(22);
s2.setdata(33);

s1 and s2 are the objects of class student. the syntax s1.setdata(22) set the value of roll to 22. As method setdata()  is a method. It can only be access using its own object. To access the member funciton dot (.) links the object and member functions.

Objects s1 and s2 has its own data members and each objects data is stored in its own memory.