Objects



   Objects



1.   Creating Objects
An object is an instance of class. Once a class has been declared, we can create variables of that type by using class name. An object occupies memory space.

For Example: -

Item x;                                   // memory for x is created

creates a variable x of type Item. In C++, the class variables are known as objects. Therefore, x is called an object of type Item, we may also declare more than one object in one statement,
Example:

Item x, y, z;

The declaration of an object is similar to that of a variable of any basic type. The necessary memory space is allocated to an object at this stage. Note that class specification, like a structure, provides only a template and does not create any memory space for the objects.

Objects can also be created when a class is defined by placing their names immediately after the closing brace, as we do in the case of structures. That is to say, the definition

Class Item
{
      ……..
      ……..
      ……..
} x,y,z;

would create the objects x, y and z of type Item . This practice is seldom followed because we would like to declare the objects close to the place where they are used and not at the time of class definition.


2.   Accessing Class Member
The private data of a class can be accessed only through the member functions of that class. The main ( ) cannot contain statements that access number and cost directly. The following is the format for calling a member function:

Object-name. Function-name (actual -arguments);

For example, the function call statement
x.getdata(100, 75.5) ;

is valid and aligns the value 100 to number and 75.5 to cost of the object x by implementing the getdata ( ) function.


Similarly, the statement

x.putdata ( );

would display the values of data members. Remember, a member function can be invoked only by using the objects of the same class. The statement like

getdata (100, 75.5);
has no meaning. Similarly, the statement

x.number = 100;
is also illegal. Although x is an object of the type Item to which number belongs, the number (declared private) can be accessed only through a member function and not by the object directly.

It may be recalled that objects communicate by sending and receiving messages. This is achieved through the member functions. For example,

x.putdata( ) ;

sends a message to the object x requesting it to display its contents.

A variable declared as public can be accessed by the objects directly.
Example:

class xyz

{

int x:
ini y,
public:
int z;

};

-----

xyz p;

p.x=0               // error, x is private

p.z=10             // OK, z is public

The use of data in this manner defeats the very idea of data hiding and therefore should be avoided.

Comments

Popular posts from this blog

ASCII / ISCII / UNICODE

CISC / RISC / EPIC

Evolution of Computers