Class Objects

A class specification only declares the structure of objects and it must be instantiated in order to make use of the services provided by it. This process of creating objects (variables) of the class is called class instantiation. It is the definition of an object that actually creates objects in the program by setting aside memory space for its storage. Hence, a class is like a blueprint of a house and it indicates how the data and functions are used when the class is instantiated. The necessary resources are allocated only when a class is instantiated. The syntax for defining objects of a class is class classname objectname,...; . Note that the keyword class is optional.

Accessing a Class Members
 
Once an object of a class has been created, there must be a provision to access its members. This is achieved by using the member access operator, dot(.). the syntax for accessing members (data and functions) of a class is shown below 

 Objectname . datamember
 Objectname . functionname(actual arguments)

If a member to be accessed is a function, then a pair of parentheses is to be added
following the function name. The following statements access member functions of
the object s1, which is an instance of the student class:
 
 S1.setdata(10,”Rajkumar”);
 S1.outdata();

The program student.cpp illustrates the declaration of the class student with the operations on its objects.

// student.cpp: member functions defined inside the body of the student class 
#include <iostream.h>
#include<string.h>
class student
{
 private:
  int roll_no;  // roll number
  char name[20]; // name of a student
 public :
  // initializing data members
  
  void setdata(int roll_no_in,char *name_in)
  {
   roll_no = roll_no_in;
   strcpy(name,name_in);
  } 
  
  // display data members on the console screen
  
  void outdata()
  {
   cout << “Roll No = “ << roll_no <<endl;
   cout << “Name =” << name << endl;
  }
}; 
void main()
  student s1;   // first object / variable of class student
  student s2;   // second object / variable of class student
  s1.setdata(1,”Tejaswi”); // object s1 calls member setdata()
  s2.setdata(10,”Rajkumar”); // object s2 calls member setdata()
  cout << “Student details ...” << endl;
  s1.outdata();   // object s1 calls member function outdata()
  s2.outdata();   // object s2 calls member function outdata()
}

Run
Student details ...
Roll No = 1
Name = Tejaswi
Roll No = 10
Name = Rajkumar