-3

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???

AOquaish
  • 53
  • 1
  • 3
  • 8
Nikhil Singh
  • 81
  • 10
  • There is one problem, `mat` is never assigned or initialized. But for the semantic of this code, there is nothing special here: a `server` that can be asked for some `material` with which you can do something `test_func`. – Jean-Baptiste Yunès Jul 02 '15 at 05:40
  • @Jean-BaptisteYunès Can you explain from output of program how Server() called is displayed before Handler() called. I didn't get this. as per my understanding first Handler() should get called. – DigviJay Patil Jul 02 '15 at 06:57
  • @DigviJayPatil, All members are initialized before the body of the constructor. If you don't do it yourself, they get default-initialized, which means calling the default constructor for `svr`. – chris Jul 02 '15 at 13:35
  • @chris Thanx for your help. – DigviJay Patil Jul 03 '15 at 04:07

1 Answers1

1

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();

Sreeraj Chundayil
  • 5,548
  • 3
  • 29
  • 68