How does object visibility work in Pascal?

Pascal objects can either have public, private, or protected members. All members are public by default.

  • Public members are visible to any unit outside the scope of the object

  • Private members are visible only within the module where the object has been declared

  • Protected members are only visible to objects that inherit from the base object, even if they are in different modules.

Let’s see an example of each:

Example

Type
Vector2D = Object
x, y : integer;
function Length: real;
end;
function Vector2D.Length(): real;
begin
Length := Sqrt(x*x + y*y);
end;
var
myVector : Vector2D;
begin
myVector.x := 5;
myVector.y := 3;
writeln(myVector.Length());
end.

In the above code, we create an object called myVector. myVector stores the x-coordinate and the y-coordinate in the member variables x and y, and a member function Length. Since all member variables and functions are public by default, we can access them from outside the scope of the object itself as seen above. We can access and set the member variables from the main code block.

However, if we were to have:

Type
    Vector2D = Object
        private
           x, y : integer;
        public
           function Length: real;
    end;

This would still be visible outside the object but not outside the module. In other words, if we replaced the example code with the above snippet, the code would still work because it is in the same module.

Similarly, if we were to have protected members, they would only be visible in the descendent objects.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved