Monday, May 2, 2016

More description Related to Member Function,Array of Object and some extra topics

Accessing private member function of the class:

It is normal way to declare all the data items in a private section and all the function in public.In some situation, certain function required to be hidden like private data from outside call. Example: Task such as deleting an account from a customer file.
Private member function can only be called by another function (i.e. a member of its class). Even an object cannot involve a private function by using dot operator.
Example:
Class student 
{int roll;
void read()
{cin>>roll;}
public:
void update()
{read();}
void display()
{cout<<roll;
}
};
void main()
{student s; 
s.update();
s.display();
s.read();---->>> //error because read() is private.
getch();
}

Characteristics of member function:

Some special characteristics of member function are as follows:
1. Member function can access private data of the class.
2. A non-member function cannot do so except to friend function.
3. A member function can call another member function directly without using dot operator.
4. Private member function cannot be accessed by the object of its class.

Array of Object:

Array is a collection of similar data type. We can have an array of user defined data type i.e. class. Such as variable are called array of object like structure. We can use array of class.
Example:
void main()
{student s[27];
int i;
for (i=0;i<27;i++)
{
s[i].read data();}
for(i=0;i<27;i++)
{
s[i].display data();
}
getch();
}

Sample Program: 

Question: Create a class employee that contain emp name (string) and emp id(long). Include a member function called getdata() to get the data from the user and another function called putdata() to display the data. Write a main function to exercise this class. It should create an array of type employee and then invite the user to input data for 100 employees. Finally it should print data of all employees.

Solution:

#include<iostream.h>
#include<conio.h>
class employee
{private:
char empname[50];
long int empid;
public:
void getdata();
void putdata();
};
void employee::getdata()
{cout<<"enter name and id of 100 employee";
cin>>empname>>empid;
}
void employee::putdata()
{
cout<<empname<<empid;
}
void main()
{
employee e[100];
int i;
for(i=0;i<100;i++)
{e[i].getdata();
}
for(i=0;i<100;i++)
{e[i].putdata();
}
getch();
}

Extra Topics:

Class, Object and Memory:

When a class is specified memory space for all the member function is allocated but memory allocation is not done for data member. When an object is created, memory allocation for its data member is done. The logic behind separate memory allocation for member function is quite obvious. All the instances of a particular class would be using the same member function but they may be storing different data in their data member.

No comments:

Post a Comment

Popular Posts