Defining a class in C++ | Declaring object in C++



Defining a class in C++ | Declaring object in C++

Class is defined as a user defined data type that contains variables called data members and functions known as member functions of the class.

Syntax of declaring a class is:

class  <class_name>
{
  private:
            [data members;]
            [member functions]
  protected:
            [data members;]
            [member functions]
  public:
            [data members;]
            [member functions]
};

class is a a keyword to specify that the class is created.

class_name refers to a user defined name given to class according to C++ identifier rules. It can be used to declare objects of the class.

Data members are the variables declared inside the class. Every object of class has individual copy of data members. 

Member functions  are the functions defined inside the class. They are used to work with data members and perform other operations within a class.  Objects of class can work through member functions of class only. 

Example:

class student
{
private:
  int rollno;
protected:
  char name[20];
public:
  void read()
  {
   cout<<"Enter rollno=":
   cin>>rollno;
   cout<<"Enter name=";
   cin.getline(name,20);
  }
  void show()
  {
   cout<<"Rollno="<<rollno;
   cout<<"\nName="<<name;
  }
};

Declaring object of class

To use the members of a class, a variable of class must be declared. This variable is known as object of class.

Example:

student obj;

The above statement will create object obj of class named student.

public members of this class can be accessed through this object. We can use dot (.) operator to access class members through object.

Syntax:

obj.member_name;

Here obj is the name of object.

Member_name refers to data member or member function that we need to access through the class object.

Example:

Object of above class can be created within any function as:

void disp()
{
  student obj;  
  //Object obj of class student within function disp().
  obj.read();   
  //public member function read() called through object obj.
  obj.show();   
  //public member function show() called through object obj.
}
int main()
{
  student obj1; 
  //Object obj1 of class student within main() function.
  obj1.read();  
  //public member function read() called through object obj1.
  obj1.show();  
  //public member function show() called through object obj1.
}

Complete Program

Example:

class student
{
private:
  int rollno;
protected:
  char name[20];
public:
  void read()
  {
   cout<<"Enter rollno=":
   cin>>rollno;
   cout<<"Enter name=";
   cin.getline(name,20);
  }
  void show()
  {
   cout<<"Rollno="<<rollno;
   cout<<"\nName="<<name;
  }
};
int main() 
{ 
  student obj1; 
  obj1.read(); 
  obj1.show(); 
  return 0;
}



Spread the love
Lesson tags: Declaring object in C++, Defining a class in C++
Back to: C++ Programming Notes
Spread the love