Nesting
of member functions
You
know that only the public members of a class can be accessed by the object of
that class, using dot operator. However a member function can call another
member function of the same class directly without using the dot operator. This
is called as nesting of member functions.
A
member function can call another member function of the same class for that you
do not need an object.
#include<iostream>
using namespace std
class nest
{
int a;
int square_num( )
{
return a* a;
}
public:
void input_num( )
{
cout<<”\nEnter a number ”;
cin>>a;
}
int cube_num( )
{
return a* a*a;
}
void disp_num()
{
int sq=square_num(); //nesting of member function
int cu=cube_num(); //nesting of member function
cout<<”\nThe
square of “<<a<<” is ”
<<sq;
cout<<”\nThe
cube of “<<a<<” is ”
<<cu;
}
};
int main()
{
nest n1;
n1.input_num();
n1.disp_num();
return 0;
}
Enter a number 5
The square of 5 is 25
The cube of 5 is 125
In
the above program disp_num() function
calls two other member function square_
num() and cube_num(). Both are defined in different visibility mode.
If
there are multiple variables with the same name defined in separate blocks then
:: (scope resolution) operator will reveal the hidden file scope(global)
variable.
Recall
:: is also used to identify the class to which a member function belongs to.
#include<iostream>
using namespace std;
int a=100;
class A
{
int a;
public:
void fun()
{
a=20;
a+=::a; //using global variable value
cout<<a;
} };
int main()
{
clrscr(); A a1;
a1.fun();
retun 0;
}
120
Recall
:: is also used to identify the class to which a member function belongs to.
In
the above program the class data member and the global variable have same name.
To
use the global variable :: used.
Related Topics
Privacy Policy, Terms and Conditions, DMCA Policy and Compliant
Copyright © 2018-2023 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.