3.3 Creating Objects
3.3 Creating Objects
3.3 Creating Objects
3 Creating Objects:-
Once a class has been declared, we can create variables of that type by
using the class name. 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;
Class item
{
….
….
….
} x, y, z;
1
3.4 Accessing class Members:-
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:
x. getdata (100,75.5);
is valid and assigns the value 100 to number and 75.5 to cost of the
object x by implementing the getdata ( ) function. Similarly, the
statement
x.putdata ( );
x. number = 100;
2
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 ( );
Class xyz
{
int x,y;
public:
int z;
};
……
…...
xyz p;
Note that the use of data in this manner defeats the very idea of data
hiding and therefore should be avoided.
3
3.5 Defining Member Functions:-
Member functions can be defined in two places:
. Outside the class definition
. Inside the class definition
3.5.1 Outside The Class Definition:-
They should have a function header and a function body. The general
form of a member function definition is:
Class item
{
int number;
float cost;
public:
void getdata (int a, float b ); // declaration
// inline function
void putdata (void) // definition
{
cout << number << “\n”;
cout << cost << ”\n”;
}
};
When a function is defined inside a class, it is treated as an inline
function.
5
3.6 A C++ program with class:-
};
//………………..Member Function Definition ………………………
void item :: getdata ( int a , float b ) // use membership label
{
number = a ; // private variables
cost = b; // directly used
}
// ……………………….Main Program …………………………….
main( )
{
item x; // create object x
cout << “\n object x “ << “ \n” ;
x. getdata ( 100,299.95 ); // call member function
6
x.putdata ( ); // call member function
object y
number : 200
cost :175.5