creating Objects
Remember that the declaration of item as shown above does not define any objects of items but only specifies what they will contain..
Once a class has been declared we can create variables of that type by using the class name for example
class declaration would look like
student
{
fees;
roll;
:
getdata( f, r);
displayData();
};
student s;
|
creates a variable name x of type item. In C++ language the class variables are known as objects. Therefore s is called an object of type student. we may also declare one or more than one objects in one statement
For Example
item s,y,z;
The declaration of an object is same to that of a variable of any basic type. The Required 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 structure. That is to say the definition
for example
student
{
……..
……..
…….
}s,y,z;
|
would create the objects s,,y,z and 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 time of class definition
Accessing Class Members
As pointer out earlier the private data of a class can be accessed only through the member functions of that class. The main() cannot contain statements that access fees and roll directly. in the below are format for calling a member function:
for example, The function call statement s.getdata(200,89);
is valid and assigns the value 200 f and 89 to r of the object s by implementing the getdata() function. The assignment occur in the actual function
and similar the statement
s.displayData();
would display the value of data members. Remember a member function can be invoked only by using an object (of the same class).
The statement like A variable declared as public can be accessed by objects directly. Example
Xyz
{
x;
y;
:
z;
};
xyz p;
p.x=9; // error , because x is private
p.z=23; // its ok, because z is public
|
Note: the use of data in this manner defeats the very idea of data hiding and therefore should be avoided