In C++, it is also possible to call a member function within another member function. This is called nested member functions.
In general, an object of a class can call any member
functions of that class using dot operator. When we used nested
functions, a function is calling inside another function and do not need the
object name.
A member function can directly call another function of the
class without object.
Example:
#include<iostream.h>
#include<conio.h>
class sample
{
private:
int a,b;
public:
void getdata()
{
cout<<"Enter a and b values : ";
cin>>a>>b;
}
int total()
{
return a+b;
}
float avg()
{
return total()/2.0;
}
void show()
{
cout<<"Total :
"<<total()<<endl;
cout<<"Average : "<<avg()<<endl;
}
};
void main()
{
clrscr();
sample s;
s.getdata();
s.show();
getch();
}
In
the above program, data members of the class are directly accessed by the member
functions. Member functions do not need the dot(.) operator to
use data members. Similarly when we call a member function from another member
function, we do not need the object name of the object or the dot(.)
operator. The member function can be directly called by using its name along
with arguments.
No comments:
Post a Comment