NAME

Objects - Object-Oriented Programming in Bash++

SYNOPSIS

@ClassName objectName
@ClassName* objectPointer=@new ClassName

@objectName.methodName argument1 argument2 ...
@objectPointer.methodName argument1 argument2 ...

echo @objectName.variableName
echo @objectPointer.variableName

echo @objectName.methodName # Calls the method in a supershell and substitutes the result

@objectName.variableName=value

echo &@objectName # Echoes the address of the object
echo @objectName # Calls the toPrimitive method
echo *@objectPointer # Dereferences the pointer and calls the toPrimitive method

@delete @objectName
@delete @objectPointer

DESCRIPTION

Bash++ objects are instances of classes that encapsulate data and behavior. They are created from class definitions and can have their own state and methods. Objects are the fundamental building blocks of object-oriented programming in Bash++.

Creating and deleting an object

When you create an object, Bash++ automatically calls the constructor of the class to initialize the object.

The destructor of the class is then called if:

Destructors are never called for objects created with @new until the object is explicitly deleted using @delete.

Destructors for global-scope objects are not run at program termination. This is to avoid non-deterministic behavior in forked processes. If you need to ensure that destructors are called for global-scope objects, you should call them explicitly using @delete.

An object “going out of scope before the program exits” means that the object is no longer accessible in the current context, i.e., the object was local to a function or method which has returned, or the object was created in a block that has ended.

Accessing object methods and variables

To access methods and variables of an object, you can use the dot notation. For example, if you have an object myObject of class MyClass, you can access its method myMethod and variable myVariable like this:

@myObject.myMethod argument1 argument2 ...
echo @myObject.myVariable

The dot signals that we are descending the object hierarchy to access something internal to the object. For example, myObject can contain another non-primitive innerObject, and you can access its method innerMethod like this:

@myObject.innerObject.innerMethod argument1 argument2 ...

The notation for descending into an object’s methods or variables is the same for both objects and pointers to objects. You do not need to use the spooky -> operator in the case of pointers. Bash++ pointers are automatically dereferenced as needed.

Referencing an object in a place where a primitive is expected (e.g., in an echo command) will implicitly call the object’s toPrimitive method. All classes in Bash++ have a toPrimitive method, which is used to convert the object to a primitive value. This method can be overridden to provide custom behavior.

SEE ALSO