Nesting of member functions: We know that a member function of a class can be called only by an object of that class using a
dot operator. However, there is an exception to this. A member function can be called by using its name
inside another member function of the same class. This is known as nesting of member function. Example: #include using namespace std;
class set
{
int m,n;
public:
void input(void);
void display(void);
int largest(void);
};
int set :: largest(void)
{
11
if(m >= n)
return(m);
else
return(n);
}
void set :: input(void)
{
cout << "Input value of m and n"<<"\n";
cin >> m>>n;
}
void set :: display(void)
{
cout << "largest value=" << largest() <<"\n";
}
int main()
{
set A;
A.input();
A.display();
return 0;
}
Object as function arguments: Like any other dta type, an object may be used as a function argument. This can be done in two ways.
i)
A copy of the entire object is passed to the function.
ii)
Only the address of the object is transferred to the function
First method is pass-by-value. Since a copy of the object is passed to the function, any changes made to
the object inside the function do not affect the object used to call the function. The second method is
called pass-by-references. When an address of the object is passed, the called function works directly on
the actual object used in the call. This means that any changes made to the object inside the function
will reflect in the actual object. The pass-by reference method is more efficient since it requires to pass
only the address of the object and not the entire object.
Example program of object as function argument:
Example 1
12
#include using namespace std;
class time
{
int hours;
int minutes;
public:
void gettime(int h, int m)
{
hours=h;
minutes=m;
}
void puttime(void)
{
cout<< hours<<"hours and ";
cout<}
void sum( time ,time);
};
void time :: sum (time t1,time t2)
{
minutes=t1.minutes + t2.minutes;
hours=minutes%60;
minutes=minutes%60;
hours=hours+t1.hours+t2.hours;
}
int main()
{
time T1,T2,T3;
T1.gettime(2,45);
T2.gettime(3,30);
T3.sum(T1,T2);
cout<<"T1=";
T1.puttime( );
cout<<"T2=";
T2.puttime( );
cout<<"T3=";
T3.puttime( );
return(0);
}
13
Output:
Example 2
#include using namespace std;
class Demo
{
private:
int a;
public:
void set(int x)
{
a = x;
}
void sum(Demo ob1, Demo ob2)
{
a = ob1.a + ob2.a;
}
void print()
{
cout<<"Value of A : "<}
};
int main()
{
//object declarations
Demo d1;
Demo d2;
Demo d3;
//assigning values to the data member of objects
d1.set(10);
d2.set(20);
14
//passing object d1 and d2
d3.sum(d1,d2);
//printing the values
d1.print();
d2.print();
d3.print();
return 0;
}
Output: