Coupon Accepted Successfully!


Declaring Objects

A class declaration only builds the structure of an object. The member variables and functions are combined in the class. The declaration of objects is same as declaration of variables of basic data types. Defining objects of class data type is known as class instantiation. Only when objects are created, memory is allocated to them.

Consider the following examples.


a) int x,y,z; // Declaration of integer variables

b) char a,b,c; // Declaration of character variables

c) item a,b, *c; // Declaration of object or class type variables

In the example (a), three variables x, y, and z of int types are declared. In the example (b), three variables a, b, and c of char type are declared. In the same fashion the third example declares the three objects a, b, and c of class item. The object *c is pointer to class item.

An object is an abstract unit with the following properties:

  1. It is individual.
  2. It points to a thing, either physical or logical that is identifiable by the user.
  3. It holds data as well as operation method that handle data.
  4. Its scope is limited to the block in which it is defined.

Access to class members: The object can access the public data member and member functions of a class by using dot (.) and arrow (->) operators. The syntax is as follows:

[Object name][Operator][Member name]

To access data members of class the statement would be as follows:


where a is an object and show() is a member function. The dot operator is used because a is a simple object.

In statement


*c is pointer to class item; therefore, the arrow operator is used to access the member.


Consider the given example.

class item // class declaration


int codeno;

float prize;

int qty;


We replaced the struct keyword with class. If programs 8.1 and 8.2 are executed with class, they will not work. For example,


void main()


item a,*b; // object declaration


a.codeno=123; // Direct access is not allowed


a.qty= 150;


The above program will generate error messages such as “‘item::codeno’ is not accessible”. This is because the object cannot directly access the member variables of a class, which is possible with structure. Hence, we can say that the difference between class and struct is that the member variables of struct can be accessed directly by the object, whereas the member variables of class cannot be accessed directly by the object.

Test Your Skills Now!
Take a Quiz now
Reviewer Name