Search code examples
ooppascalparadigmsdelphi

Create parent/child relationship in class


I have two classes, a child class:

type MyChildClass = class
public
parent: ^MyParent;
end;

And a parent class:

type MyParentClass = class
public
childs: array of ^MyChildClass;
end;

However, this wont work since only the class declared the last knows the other one. Example:

program Test;

interface

type MyChildClass = class
public
parent: ^MyParentClass;
end;

type MyParentClass = class
public
childs: array of ^MyChildClass;
end;

implementation

end.

This wont compile because the 7th line will throw the error "Undeclared identifier 'MyParentClass' as expected. Using abstract classes only solves the problem partially. Im really struggling on finding a solution. Maybe using interfaces would help?


Solution

  • Pascal is a single pass-compiled language, therefore the compiler scans only once a single file: in every moment it has to know each identifier. When you are creating a circular reference, like in this case, you are referencing a class written after the current one which is not permitted. To fix this issue, you need to use the so called forward declaration, i.e. you are declaring (promising) to the compiler that somewhere in your code it will find this identifer (look at the code, problem1).

    Additionally, you are defining multiple different type scopes (by writing type multiple times). Each type scope has it's own types (and a type defined in a scope cannot be seen by another scope), hence, you need to define a single one (look at the code, problem2).

    program Test;
    
    interface
    
    type // declare a single type scope (problem 2)
        MyParentClass = class; // this is the forward declaration (problem 1)
    
        MyChildClass = class
        public
            parent: ^MyParentClass;
        end;
    
        MyParentClass = class
        public
            childs: array of ^MyChildClass;
        end;
    
    implementation
    
    end.