6

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?

5

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);
    }
}
  • 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 8:58
  • @comeback4you returning tuples from struct type is not compatible with string type. Try using bytes32 instead. – GViz Oct 1 '18 at 23:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.