9

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?

jrbedard
  • 524
  • 1
  • 6
  • 15
Aditi
  • 327
  • 2
  • 8

1 Answers1

9

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);
    }
}
larsl
  • 293
  • 1
  • 10
bozzle
  • 896
  • 6
  • 13
  • I have tried above contract and got error : Untitled2:30:16: Error: Return argument type tuple(inaccessible dynamic type,uint256,bool) is not implicitly convertible to expected type tuple(string memory,uint256,bool). return student.StudentNames(ID); – comeback4you Mar 28 '17 at 08:58
  • @comeback4you returning tuples from struct type is not compatible with string type. Try using bytes32 instead. – Garen Vartanian Oct 01 '18 at 23:10