[Ethereum] Access struct object of one contract from another

contract-designcontract-developmentsoliditystruct

I have 2 contracts:

contract Student{
    uint ID;
    struct stu{
        string name;
        uint age;
        bool tookTest;
    }
    mapping(uint => stu) StudentNames;
    function Student(string _name,uint _age) {
        //ID is incremented
        stu s = StudentNames[ID];
        s.name = _name;
        s.age = _age;
        s.tookTest = false;
    }
}

contract ClassRoom {
    address studentAddr;
    Student student;
    function ClassRoom(address addr) {
        studentAddr = addr;
        student = Student(addr);
    }

    //some function that performs a check on student obj and updates the tookTest status to true
}

I don't want to inherit any contract. I want to access object of struct student of contract Student from contract ClassRoom. How to go about this?

Best Answer

In the constructor for Student, the mapping studentNames and the uint ID are not initialised. If you try to do stu s = studentNames[ID], you will just get 0. You want something like the following:

contract Student{
    struct stu{
        string name;
        uint age;
        bool tookTest;
    }
    mapping(uint => stu) public studentNames;
    function addStudent (uint ID, string _name, uint _age) {
        studentNames[ID] = stu(_name, _age, false);
    }
    function updateStudent (uint ID) {
        studentNames[ID].tookTest = true;
    }
}

You can access the mapping from outside the contract if you declare it as public, as above. Note that this only gives READ access. You will still need a function in the Student contract to update the tookTest member.

e.g.

contract ClassRoom {
    address studentAddr;
    Student student;
    function ClassRoom(address addr) {
        studentAddr = addr;
        student = Student(addr);
    }

    //some function that performs a check on student obj and updates the tookTest status to true
    function updateTookTest (uint ID) {
        student.updateStudent(ID);
    }
    //if you want to access the public mapping
    function readStudentStruct (uint ID) constant returns (string, uint, bool) {
        return student.studentNames(ID);
    }
}