I was going through a piece of code when I came across something new. However I tried to write my own code for better understanding.
#include<iostream>
using namespace std;
class material
{
public:
material()
{
cout<<"material() called"<<endl;
}
bool test_func()
{
cout<<"Hello World"<<endl;
return true;
}
};
class server
{
private:
material *mat;
public:
server()
{
cout<<"server() called"<<endl;
}
material *matrl()
{
return mat;
}
};
class Handler
{
public:
Handler()
{
cout<<"Handler() called"<<endl;
}
server svr;
bool demo()
{
bool ret;
ret=svr.matrl()->test_func();
return ret;
}
};
int main()
{
Handler h;
cout<<"returned by demo():"<<h.demo()<<endl;
return 0;
}
Even I am getting the desired output, which is:
server() called
Handler() called
Hello World
returned by demo():1
But I am not able to understand certain concept here :
material *matrl()
{
return mat;
}
and the functionn call
ret=svr.matrl()->test_func();
How this is working and what concept is the concept behind this ? Can somebody help me with this???
You can avoid the confusion if you rewrite
material *matrl()
{
return mat;
}
to
material* matrl()
{
return mat;
}
Both are same. It is a function returning a pointer to an object of material type
Now
ret=svr.matrl()->test_func();
since matr1()
returns a pointer to the object you need to use -> for the member function.Or
*(svr.matr1()).test_func();