/**
@page LangRef

@section ObjectProg Object Oriented Programming
<p>B++'s approach to object orientation is simpler than C++'s, even though they are syntactically similar. Nevertheless, the basic paradigms of object-oriented programming - data encapsulation, inheritance and polymorphism - are taken into account.<br>
There are also additional options, such as the construction of partial classes, the subsequent redefinition of member functions, and the definition of operators on objects.<br>
The following sections describe the principles and options.</p>

@subsection ClassStructure Structure of a class
<p>The following example shows the structure of a class in B++.<br>
It shows the beginning of a fictitious class library with a root class \c MyBaseClass and a derived class \c MyDerivedClass. All object instances of this library should have a unique identifier (\c _ID), the assignment of which is the sole task of the base class.</p>

@code{.bpp}
// Declaration of MyBaseClass
Class MyBaseClass
{
   MyBaseClass();
   uint getID() const;
   uint _ID;
   static uint createID(); 
   static uint _maxID = 0; // ID counter, initialized to zero
}

// Implementation of MyBaseClass
MyBaseClass::MyBaseClass() { _ID = createID(); }
uint MyBaseClass::getID() const { return _ID; }
uint MyBaseClass::createID() { return ++_maxID; }

// Declaration of MyDerivedClass
class MyDerivedClass : MyBaseClass
{
   MyDerivedClass(string name = "", var value = null)
   string getName() const;
   void setName(string name);
   var getValue() const;
   void setValue(var value);
   // member variables
   string _name;
   var _value; 
}

// Implementation of MyDerivedClass
MyDerivedClass::MyDerivedClass(var name = "", var value = null)
{
   MyBaseClass();
   _name = name;
   _value = value;
}
var MyDerivedClass::getName() const { return _name; }
void MyDerivedClass::setName(var name) { _name = name; }
var MyDerivedClass::getValue() const { return _Value; }
void MyDerivedClass::setValue(var value) { _value = value; }
@endcode

<p>At first glance, the class declarations and implementations are similar to what you are used to in C++. However, there are a number of important differences:</p>
<p><b>Visibility of elements</b></p>
<p>In B++, member and class functions as well as class variables (\c static) are implicitly \c public without explicit access specifiers.<br>
Member variables are implicitly \e protected, i.e. they are only visible in the declaring class and its derivatives.</p>
<p>The keywords \c public, \c protected, and \c private are available to explicitly specify access, and the same rules apply as in C++.</p>
<p>Unlike C++, there are no \c friend declarations, so there is no way to override the access rules for individual "foreign" classes or functions.</p>
<p><b>No multiple inheritance</b></p>
<p>Unlike C++, a B++ class has at most one base class. There is also no interface concept like in Java or C#.<br>
Inheritance itself is always public, i.e. all public members of the base class also become public members of the derived classes.</p>
<p><b>Declaring variables and methods</b></p>
<p>In B++ classes, declaration of member functions in the class declaration is optional. For example, \c MyDerivedClass in the example above could have been declared as follows:</p>
@code{.bpp}
class MyDerivedClass : MyBaseClass
{
	string _name;
	var _value;
}
@endcode
<p>This allows you to add methods to classes later, if necessary.</p>
<p>Member variables and all static members must be declared.</p>
<p>If the \c static modifier appears before a comma-separated list of variables, it applies to all of its elements.</p>
@note As a result of the optional declaration of methods and the ability to redefine methods later, argument lists (and also default arguments) specified in the later implementation completely replace those listed in the declaration, if any. Therefore, unlike e.g. in C++, standard argument values must also be specified in the method head during implementation - see example at start of this section.

<p><b>Element constants and constant methods</b></p>
<p><i>Element constants</i> are implicitly static, i.e. defined at the class level. The modifier \c static in the declaration is therefore optional and only serves for syntax compatibility with C++. Like static variables of a class, element constants must be listed in the class declaration. They are always initialized at compilation time, which means that an element constant must always be initialized with a literal or a literal expression.</p>
<p>Like in C++, <i>constant methods</i> are declared with a \c const following the argument list. Just like in C++, constant methods must always be real member functions (i.e. not \c static).<br>
Within such a method, the \c this reference is considered constant, so normally no member variables can be changed.<br>
An exception to this is, as in C++, member variables that are declared with the \c mutable modifier.</p>
@note Unlike in C++, calling functions that are not declared as \c const is also possible from constant objects. Errors are generated only when element variables that are not marked as \c mutable are modified. This behavior is necessary in order to be able to continue using existing methods from older versions (without \c const and \c mutable) as well as native methods.

<p><b>Restricted initialization of class variables</b></p>
<p>In B++, member and class variables (static members) can be initialized when they are declared, with the initialization taking place at compile time and not at runtime. Therefore, only literals (and not function calls) can be used for initialization. The initialization must always be noted within the class declaration (see \c _maxID in \c MyBaseClass above).</p>
<p><b>Objects are always dynamically created</b></p>
<p>All instances of classes (objects) have the internal type \c object and are therefore \ref ReferenceTypes "reference types". The only way to create them is using the new operator:</p>
@code{.bpp}
var myObj = new MyDerivedClass("number",1000);
@endcode
<p>Technically, this also applies to statically typed object variables that are initialized at definition. The notation</p>
@code{.bpp}
MyDerivedClass myObj("anumber",1000);
@endcode
is nothing more than a shortened notation for
@code{.bpp}
MyDerivedClass myObj = new MyDerivedClass("number",1000);
@endcode
<p>Therefore, it is not possible to create variables of this type directly after a class declaration, as in C++, which also explains why there is no need for a semicolon after the closing parenthesis of the class declaration (notation of a semicolon is allowed to make documentation tools happy).</p>
<p>It should also be noted that, unlike in C++, assigning to a statically typed object variable for initialization does not construct an object.</p>
@code{.bpp}
MyDerivedClass myObj = "anumber"
@endcode
would only lead to an error, because it tries to assign a string to an object variable of type \c MyDerivedClass.

@subsection ClassInlineDef Inline Definition of Classes
<p>B++ also allows classes to be fully or partially defined "inline", i.e. the implementation of a class's methods can be noted directly in the class definition. The following example shows a modification of the \ref ClassStructure "above" example, where access specifiers are also used.</p>
@code{.bpp}
// definition of MyBaseClass
class MyBaseClass
{
private:
   uint _ID;
   static uint _maxID = 0;   // ID counter, initialized to zero
public:
   static uint createID() { return ++_maxID; } 
   MyBaseClass() { _ID = createID(); }
   uint getID() { return _ID; }
}

// definition of MyDerivedClass
class MyDerivedClass : MyBaseClass
{
private:
   string _name;
   var _value; 
public:
   MyDerivedClass(string name = "", var value = null)
   {
      MyBaseClass();
      _name = name;
      _value = value;
   }
   string getName() { return _name; }
   void setName(string name) { _name = name; }
   var getValue() { return _value; }
   void setValue(var value) { _value = value; }
}
@endcode
<p>Note that all elements of a class that are used within an inline implementation must be <i>declared before they are used</i>, that is, they must be listed in the class definition before the method.</p>
<p>Inline implementation usually results in a shorter and sometimes clearer notation. The separation of declaration and definition (implementation), on the other hand, is preferable when a class interface is to be provided as a public part of a library.</p>

@subsection CtorDtor Constructors and Destructors
<p>A constructor is a special member function of an object whose main task is to initialize the member variables with appropriate initial values when the object is created.</p>
<p>In B++, as in C++, a constructor has the same name as its class. Since function overloading is not possible, a class can have only one constructor. This constructor must return a reference to the created object. In the original version of \ref Intro "BOB" this meant that a constructor always hatd to be left with the statement</p>
<pre><tt>return this;</tt></pre>
<p>The B++ compiler automatically appends the corresponding bytecode to the end of each constructor function, so that the statement only needs to be noted here if the constructor is left prematurely (due to an exit condition).</p>
<p>Unlike e.g. in C++, a constructor in B++ does not automatically call the constructor of an existing base class. Such a call must be coded explicitly. An example to illustrate:</p>
@code{.bpp}
class Base
{
   Base();
}

Base::Base()
{
   print(ctor of Base called\n);
}

class Derived : Base
{
   Derived();
}

Derived::Derived
{
   Base();
   print(ctor of Derived called\n);
}

main()
{
   var obj = new Derived();
   // do anything
   obj = null;  // releases object 
}
@endcode
@note <ul>
<li>In B++, the constructor can also be called like a normal member function if necessary.</li>
<li>You cannot create instances of a class that does not have its own constructor. This property can be used to define abstract classes. As an alternative, a constructor can also be declared <tt>protected</tt> to prevent the creation of object instances.</li>
</ul>
<p>A destructor is, in a sense, the opposite of the constructor. It is used to free any external resources that an object may had occupied (additional memory, open files, etc.) when it is destroyed.</p>
<p>B++ essentially adopts the concept of destructors from C++. Specifically, this means</p>
<ul>
<li>A destructor is declared as a parameterless member function with the class name preceded by a tilde (~).</li>
<li>The destructor is automatically called just before the object is destroyed, i.e. inside the destructor all elements (including the <tt>this</tt> reference) are still valid.</li>
<li>At the end of the destructor function, the destructors of all base classes are also called recursively, i.e. the destructor code of the derived class is always executed <i>before</i> that of the base class. Classes without destructors are skipped in the class hierarchy.</li>
</ul>
<p>For clarity, the above example is extended:</p>
@code{.bpp}
class Base
{
   Base();
   ~Base();
   getClassName();
}

Base::Base() {
   print(ctor of Base called\n);
}

Base::~Base() {
   print(dtor of Base called\n);
}

Base::getClassName() { return Base; }

class Derived : Base
{
   Derived();
   ~Derived();
   getClassName();
}

Derived::Derived {
   Base();
   print(ctor of Derived called\n);
}

Derived::~Derived {
   print(dtor of Derived called\n);
}

Derived::getClassName() { return Derived; }

main() {
   var obj = &new Derived();
   // do anything
   obj = delete obj; 
}
@endcode
@note <ul>
<li>In the example, the unary operator <tt>&amp;</tt> is used when assigning the derived instance to the variable \c obj to force explicit memory management. This is done only to demonstrate the use of the \c delete operator. Normally, one would use a simple assignment that would automatically free obj when the function exits.</li>
<li>The \c delete operator always returns \c null in B++. It can therefore be used - as here in the \c main function - as the right expression of an assignment to mark the freed variable as invalid.</li>
<li>Due to implementation, B++ maps the destructor to a member function with the reserved identifier <tt>\e dtor</tt>. As an alternative to the C++-compliant notation, this identifier can also be used for the declaration/definition of the destructor. In addition, the destructor can be called with this name like a normal member function (Caution: The destructors of the base classes are also called here!).</li>
</ul>

@subsection MemberAccess Accessing Member Functions and Variables Within a Class
<p>If the implementation of a member function contains function calls or variable accesses, a suitable element is first searched for in the current class and, if necessary, in its base classes. If the search is unsuccessful, the function or variable identifier is assumed to be a global identifier. If the identifier is preceded by the keyword \c this followed by the method call operator (<tt>-&gt;</tt>), the identifier is searched only in the respective object.</p>
<p>The behavior is similar for static elements, but to specify a concrete class, the class name and the scope resolution operator (<tt>::</tt>) are specified before the actual identifier.</p>
In this context, the problem arises that implementing a member function may require access to a global symbol (variable or function) with the same name as an element of the current class.<br>
In B++, as in C++, access to global symbols can be forced using the range resolution operator, as shown in example below.</p>
@code{.bpp}
// globally defined function 
message() { print("global function message called\n") };

class MyClass
{
   MyClass();
   message();    // member function message
   doAction();
}

MyClass() {}
MyClass::message() { print(function MyClass::message\n);}
MyClass::doAction(;obj)
{
   message();          // call internal message method
   this->message();    // call internal message method, 
                       // search in current class only
   ::message()         // call global function message
}
@endcode

@subsection VirtualMethods Virtual Methods
<p>In B++, there is no "early binding" in the strict sense (Section \ref ExtendedCallSyntax "below" describes how such behavior can still be achieved.). This means that all methods of a class, even static ones, are virtual. Let's take a look at \ref "example of destructor calls", and change its \c main function to the following</p>
@code{.bpp}
main()
{
   var obj = new Base();
   print(obj->getClassName(),"\n");
   obj = new Derived();
   print(obj->getClassName(),"\n");
}
@endcode
<p>Here instances of the \c Base or \c Derived classes are assigned one after the other to the same variable (<tt>obj</tt>) and their <tt>getClassName()</tt> methods are called. The first call activates the original version from \c Base and the second call activates the overridden version from \c Derived.</p>
<p>It often happens that a derived class overrides a method of its base class to extend its functionality, but not to replace it completely. Then it is desirable to simply call the contents of the inherited method instead of reimplementing it completely. B++ uses a special syntax for this:</p>
<p><i>To call the inherited ancestor method within the implementation of an overriding method, the function name is prefixed with \c BC_ (for BaseClass).</i></p>
@code{.bpp}
class MyBaseClass
{
   MyBaseClass();
   writeInfo();
}

MyBaseClass::MyBaseClass() {}    // ctor does nothing
MyBaseClass::writeInfo() { print("MyBaseClass::writeInfo() called\n"); }

MyDerivedClass : MyBaseClass
{
    MyDerivedClass();
    writeInfo();
}

MyDerivedClass::MyDerivedClass() {}    // ctor does nothing
MyDerivedClass::writeInfo()
{ 
   print(MyDerivedClass::writeInfo() called\n);
   this->BC_writeInfo();    // calls inherited writeInfo method
}
var main()
{
   var obj = new MyDerivedClass();
   obj->writeInfo();
   return 0;
}
@endcode
@note <ul>
<li>The inherited ancestor method must be called via the \c this pointer (see example above). Otherwise the compiler would generate an "ordinary" function call.</li>
<li>The call with the <tt><i>BC_</i></tt> prefix refers to the base class of the class that contains the calling method. Analogous to the prefix <tt><i>BC_</i></tt>, the prefix <tt><i><b>DC_</b></i></tt> (for defining class) can be used. Here the call refers to the class in which the calling method was defined. It can be used to prevent a self-recursively calling method that is overwritten in a derived class and called from there with <tt><i>BC_</i></tt> from calling the method of the derived class again in the recursion.</li>
</ul>
<p>The following example shows the method call within the implementation of methods with and without the use of \c this, as well as the use of \c BC_ and \c DC_.</p>
@code{.bpp}
class ClA
{
}
ClA::ClA() {}
ClA::test() { print("ClA::test\n"); }
ClA::callTest() {
   print("\n",__func__," called from class ",getclassname(this),"\n");
   print("this->DC_test : "); this->DC_test();
   print("this->test(); : "); this->test();
}

class ClB : ClA
{
}
ClB::ClB() {}
ClB::test() { print("ClB::test\n"); }
ClB::callTest() {
   print("\n",__func__," called from class ",getclassname(this),"\n");
   print("test() : "); test();
   try {
      print("this->BC_test : "); this->BC_test();
   }
   catch (e) { print(e,"\n"); }
   print("this->DC_test : "); this->DC_test();
   print("this->test(); : "); this->test();
   print("this->BC_callTest(); : "); this->BC_callTest();
}

class ClC : ClB
{
}

ClC::ClC() {}
ClC::test() { print("ClC::test\n"); }

void main()
{
   var obj = new ClC();
   obj->callTest();
   obj = new ClB();
   obj->callTest();
   obj = new ClA();
   obj->callTest();
}
@endcode
</ul>
<p>The simple call to the \c test method (implemented in the \c callTest methods) produces the same result regardless of whether it is prefixed or not. However, an explicit object reference (\c this) is absolutely necessary for the prefix calls.</p>

@subsection ExtendedCallSyntax Extended Syntax of the -> Operator
<p>In B++, the <tt>-&gt;</tt> operator is used exclusively to call instance methods of an object and has the general form</p>
<pre><tt>    <i>objref</i>-><i>methodname</i>(<i>argumentlist</i>)</tt></pre>
<p>In addition to this standard form (see examples in \ref VirtualMethods "section before"), there is an extended variant of the call:</p>
<pre><tt>    <i>objref</i>->(<i>expr</i>)(<i>argumentlist</i>)</tt></pre>
<p>Here, instead of the method name, an <i>expression</i> is specified that returns either the name of the method to be called as a string or a reference (in the sense of a pointer) to the code of the method to be called.</p>
<p>An expression that returns a string can be used to determine the names of methods to be called at runtime. The behavior of the method call itself is exactly the same as in the standard form; in particular, the prefixes <tt><i>BC_</i></tt> and <tt><i>DC_ </i></tt>(see \ref VirtualMethods "above") can be used too.</p>
<p>In addition, the extended form allows "early binding" of methods, i.e., their non-virtual invocation.
This can be achieved by using</p>
<pre><tt>    <i>objref</i>->(<i>classname</i>::<i>methodname</i>)()</tt></pre>
<p>where <tt><i>classname</i></tt> is the name of <tt><i>objref</i></tt>'s own class or one of its base classes, and <tt><i>methodname</i></tt> is the method to be called.</p>
<p>This means that the method to be called is not determined at runtime (as with virtual calls), but the reference to the method to be executed is integrated directly into the bytecode. Accordingly, the class and the method to be called must be (at least) declared  at the time of compiling the calling code.</p>

@subsection MethodPointers Method Pointers and Method Literals
<p>Methods of an object (element functions) differ from ordinary functions only in their relation to a class and in the possibility of accessing member variables of objects (instances of the class). Accordingly, references to methods can be assigned to variables or used as arguments of function calls. Variables that have been assigned a reference to a method can be viewed as <i>method pointers</i>, analogous to the \ref FunctionPointers "function pointers".<p>
<p>The following example shows the assignment of an element function to a variable and variants of the call.</p>
@code{.bpp}
class ClassA
{
public:
  ClassA() {}
  Test(i) { print (__func__,"(",i,")\n"); }
};

main()
{
   var obj = new ClassA();
   var a = ClassA::Test;
   obj->(a)(1);
   a(obj,1);
}
@endcode
<p>The assignment to a variable is done in the same way as for read access to a static variable in a class.
The call is made either via an object reference with the \ref ExtendedCallSyntax "extended form" of the <tt>-&gt;</tt> operator or like a simple function call, where an object must be passed as an additional (first) parameter.</p> 
<p>Methods can also be defined as literals, using the definition syntax</p>
<pre><tt>    function '['<i>classid</i>']' [<i>returntype</i>] '('<i>paramlist</i> [;<i>localvarlist</i>]')' <i>body</i></tt></pre>
<p>(see \ref AnonymousFunctions)</p>
<p><tt><i>classid</i></tt> refers to a class that must already exist (be declared) at the time of the literal definition. Furthermore, all variables belonging to the class that are used within the literal method must be defined - see example below.</p>
@code{.bpp}
class A
{
private:
   string _txt;
public:
   A(string txt="hello\n") { _txt = txt; }
}
// defines global variable g initialized with member function literal
var g = function [A] string() { return _txt; }

main()
{
   var a = new A();
   print(a->(g)());
}
@endcode 
@note The example shown here demonstrates a way to temporarily extend existing classes with additional methods. Note that this bypasses the access protection defined for the class members. Therefore, this option should be used carefully and its use should be well documented.

@subsection LocalClasses Local Classes
<p>As of version 1.5, B++ allows the 'local' definition of classes, i.e. the definition of classes as elements of another, higher-level class. Typical use cases for this are defining iterators  and encapsulating implementation details of custom container classes and other helper classes for implementation.</p>
<p>The following example demonstrates the use of local classes by implementing a simple list class with a forward iterator and an internal element type.</p>
@code{.bpp}
class SimpleList
{
   class Element 
   {
    public:
       var _value = null;
      Element _next = null;
      Element() {}
   }
   class iterator
   {
   private:
      Element _el = null;
      SimpleList _list = null;
   public:
      iterator(SimpleList list, Element el) {
         _el = el;
         _list = list;
      }
      bool equals(iterator other) {
         if (!other) return false;
         return (addr(_list) == addr(other._list) && 
                 addr(other._el) == addr(_el));
      }
      Element operator*() { return _el; }
      iterator operator++() { if (_el) _el = _el._next; return this; }
      iterator operator++(int) {
         auto res = new iterator(_list,_el);
         return ++res;
      }
      iterator next() { iterator res = clone(this}; return ++res; }
   }
private:
   Element _start = null;
public:
   SimpleList() {};
   iterator begin() { return new iterator(this,_start);} 
   iterator end() { return new iterator(this,null); }
   iterator insert(var value, iterator pos = null) {
      auto e = new Element();
      e._value = value;
      auto iter = begin();
      if (!pos || pos == iter) {
         e._next = _start;
         _start = e;
         return begin();
      }
      auto end = end();
      for (auto it=iter; it != end(); ++it;) {
          auto nxt = it->next();
          if (nxt == pos || nxt == end) {
              auto before = *it;
              e._next = before._next;
              before._next = e;
              return nxt;
          }
      }
      return end;
   }
   iterator erase(iterator pos) {
      auto iter = begin();
      auto end = end();
      if (!_start) return end;
      if (!pos || pos == iter) {
        _start = _start.next;
        return begin();
      } 
      for (auto it = iter; it != end; ++it) {
         auto nxt = it->next();
         if (nxt == pos || nxt == end) {
            auto before = *it;
            if (*nxt) {
               before._next = (*nxt)._next;
               (*nxt)._next = null;
            }
            else before._next = null;
            return ++it;
         }
      }
      return end;
   }
}
@endcode
@note Unlike methods and member variables, local classes are always public.<br>
Local classes are accessed by client code using the scope resolution operator (<tt>::</tt>).

@subsection PartialClasses Partial classes 
<p>B++ supports partial classes in a similar way to C#, but without using a special keyword.<br>
<p>A <i>partial class</i> is a class whose definition is spread over several blocks, which may be in different source files.<br>
This opens up a number of possibilities:</p>
<ul>
<li>Distribute large classes over several files</li>
<li>Deal with different aspects of a class in separate sections</li>
<li>Class content can be made variable, i.e. depending on the context, a concrete class can be composed of different parts.</li>
<li>Use for forward declaration of classes unknown at compile time of a module</li>
<li>Existing classes can be extended "later".</li>
</ul>
<p>For the following example we assume that a program uses a class \c Class1, creates an instance of it and activates a \c doAction method on it.<br>
The class \c Class1 itself is finally defined and implemented in another module, which is combined with the main program when called.</p>
<p>First the main program:</p>
@code{.bpp}
// doAction example  main module action.bpp 

class Class1      // class prototype
{
   doAction();
}

main() {
   var obj = new Class1();
   obj->doAction();
}
@endcode
<p>\c Class1 is only defined here as an empty prototype - this is what the compiler requires. A first version of the complete definition and implementation takes place in a module \c actcl1_1:</p>
@code{.bpp}
// first version of Class1 module  actcl1_1.bpp 

class Class1
{
    Class1();                        // ctor
    doAction();
    var _callCnt;                    // counter for calls of doAction     
}
// implementation

Class1::Class1() { _callCnt = 0; }
Class1::doAction()
{
   print(++_callCnt,". call of doAction in module actcl1_1\n");
}
@endcode
<p>Now you can compile the main program and the module into bytecode, and then run the main program using the library module:</p>
<pre><tt>    bp2 -c action -o action.bpm
    bp2 -c actcl1_1 -o actcl1_1.bpm
    bp2 -r action actcl1_1
</tt></pre>
<p>Without modifying the main program, you can reimplement the class Class1 in another module and use it as an alternative to the above:</p>
@code{.bpp}
// second version of Class1 module  actcl1_2.bpp

class Class1
{
    Class1();                        // ctor
    doAction();
}
// implementation

Class1::Class1() {}                  // ctor does nothing
Class1::doAction()
{
   print("doAction in module actcl1_2 activated\n");
}
@endcode
<p>The compilation and calling is done in the same way:</p>
<pre><tt>    bp2 -c actcl1_2 -o actcl1_2.bpm
    bp2 -r action actcl1_2
</tt></pre>

@subsection RedefineMemberFuncs Replacing member functions (Redefinition)
<p>Just as you can replace existing ordinary functions by simply redefining them, this is also possible for functions that are part of a class. The newly defined variant completely replaces the old one. This feature can be used to change the behaviour of a class at a later stage.<br>
The example from the previous section is used to illustrate this. However, the \c Class1 is now implemented immediately.</p>
@code{.bpp}
// doAction example  main module action.bpp 

class Class1      
{
public:
   Class1();
   doAction();
}

Class1::Class1() {}
Class1::doAction() { print("Class1::doAction called\n"); }

main()
{
   var obj = new Class1();
   obj->doAction();
}
@endcode
<p>The example should work straight away. Now write a patch module that changes the behaviour of \c Class1's \c doAction method:</p>
@code{.bpp}
// module patch.bpp replaces doAction method of Class1 
Class1::doAction()
{
   print("patched version of Class1::doAction called\n");
}
@endcode
<p>Note that the patch module cannot be compiled separately because it does not contain a declaration of \c Class1, but the following call is possible:</p>
<pre><tt>    bp2 action patch 
</tt></pre>
<p>Here the patch is compiled after the original program, so \c Class1 already exists and the compiler is happy.</p>
@note <ul>
<li>Redefining a method does not change its visibility level (\c public, \c protected, \c private).</li>
<li>The same rules apply to redefinition as to "normal" implementation of a method outside the class definition. In particular, this applies to the need to re-specify default parameters.</li>
</ul>

@subsection OperatorDefinition Defining Operators
<p>In B++ it is possible to redefine some operators for objects (or more precisely: their classes), or to define them at all.</p>
<p>An operator is defined indirectly by a class that provides a method (member function) whose name corresponds to one of the reserved identifiers of the form \c OP_XXX (see Chapter \ref KeywordsAndReserved).<br>
Alternatively, a syntax based on C++ with the keyword \c operator and a trailing operator symbol can be used for the definition. This notation is preferred because of its common use in the examples in the following sections.</p>
@note <ul>
<li>Even with \c operator notation, the compiler creates methods of the form \c OP_XXX. Therefore, explicit operator calls can only be made using these method names.</li>
<li>Like all other methods, operator functions return a value. Therefore, an operator definition can optionally be preceded by a return type.</li>
<li>Unlike C++, operators in B++ cannot be defined as global functions, but only as (non-static) member functions of classes.</li>
<li>Like all other methods, operator functions can be declared c\ const if they do not change any properties of the calling object (exception: member variables declared as \c mutable). The arguments of operator functions may also be declared as \c const.</li>
</ul>
<p>The rules for defining individual operators or groups of operators are explained below.</p>

@subsubsection DefFuncOp Defining the Function Operator
<p>When a class defines the function operator <tt>()</tt>, its instances become <i>function objects</i> (sometimes called <i>functors</i>). Such objects can be used in the program like functions.</p>
<p>The operator is defined in the form</p>
<p><tt>    <i>[returntype]</i> OP_CALL(<i>argumentlist</i>)</tt> or<br>
<tt>    <i>[returntype]</i> operator()(<i>argumentlist</i>)</tt>,</p>
<p>where <tt>\e argumentlist</tt> is a comma-separated (and possibly empty) list of argument definitions to which all the rules of an argument list of "normal" functions apply.<br>
In particular, argument lists of variable length or default parameters can also be used - see Section \ref VarListsVariable. </p>
<p>Following example illustrates the procedure using a class whose instances are used as functions that write any number of strings to a file.</p>
@code{.bpp}
// operator () example 
class StringWriter
{
public:
   StringWriter(string file);
   ~StringWriter();
   uint operator()();
private:
   FILE _fp;
}

StringWriter::StringWriter(string file)
{
   _fp = fopen(file,"wt");  // opens text file for write
}

StringWriter::~StringWriter()
{
   fclose(_fp);
}

uint StringWriter::operator()()
{
   uint n = argcnt();
   for (uint i=1;i<n; ++i)
     fputs(arg(i),_fp);
   return n;
}

main()
{
   StringWriter writer("txtfile.txt");
   writer("Hello","World");
}
@endcode

@subsubsection DefIndexOp Definition of the Index Operator
The index operator <tt>[]</tt> is normally used for indexed access to single elements of a string or container (types \c vector, \c buffer or \c charbuffer) or for access to entries of an associative container (\c dictionary) via a key.<br>
If the operator is defined for objects, two member functions are required - one for read access and one for write access. If only one of the functions is implemented, the operator works in one direction only.<br>
Unlike for the standard variants, the index argument does not necessarily have to be an integer or a string.</p>
<p>The operator is defined in the form</p>
<p><tt>    <i>[returntype]</i> OP_VREF(<i>index</i>) <i>[const]</i></tt> or<br>
<tt>    <i>[returntype]</i> operator[](<i>index</i>) <i>[const]</i></tt></p>
for read access or
<p><tt>    <i>[returntype]</i> OP_VSET(<i>index</i>, <i>value</i>)</tt> or<br>
<tt>    <i>[returntype]</i> operator[]=(<i>index</i>, <i>value</i>)</tt> or<br>
<tt>    <i>[returntype]</i> operator[var](<i>index</i>, <i>value</i>)</tt></p>
for write access.
@note The last notation is mainly for compatibility to older versions of B++. The keyword \c var is used here for syntactic distinction when defining the operator. According to the definition of the postfix increment operators in C++, it is also possible to use \c int instead of <tt>var</tt>. 

<p>The following example shows a fragment of a \c Point class representing an n-dimensional point. The point's coordinates are read and written using the index operator.</p>
@code{.bpp}
class Point()
{
   Point(uint dim);
   ~Point();
   var operator[]=(uint index, var value)
   var operator[](uint index) const;
   vector _coords; // vector of coordinates
}

Point::Point(uint dim) 
{ 
   _coords = newvector(dim);
   for (var i=0;i<dim;++i) _coords[i] = 0;
}

var Point::operator[]=(uint index, var value) { _coords[index] = value 
   _coords[index] = value; 
   return value;
}

var Point::operator[](uint index) const { return _coords[index]; }

void main()
{
   var point = new Point(2);
   point[0] = 12; // set x-coordinate
   point[1] = 4.7; // set y-coordinate
   print("x=",point[0]," y=",point[1],"\n");
}
@endcode
@note To preserve the semantics of the assignment operator, the write variant (OP_VSET) implementation should return the assigned value, as in the example above.

@subsubsection DefDotOp Defining the dot operator
<p>As already \ref DotOp "mentioned", the dot in B++ is a common operator for accessing elements of associative containers (data type \c dictionary) and public data elements of objects, which can be explicitly defined for objects or their classes, i.e. its functionality can be extended. This allows, for example, to implement access to elements of an object in the sense of properties (as used in C#) or user-defined associative containers that can be used similarly to the dictionary type.</p>
<p>The semantics of the dot operator are very similar to the index operator, so it is defined in a similar way.</p>
<p>The definition has the form</p>
<p><tt>    <i>[returntype]</i> OP_PREF(<i>key</i>) <i>[const]</i></tt> or<br>
<tt>    <i>[returntype]</i> operator.(<i>key</i>)[const]</tt></p>
for read access or
<p><tt>    <i>[returntype]</i> OP_PSET(<i>key</i>, <i>value</i>)</tt> or<br>
<tt>    <i>[returntype]</i> operator.=(<i>key</i>, <i>valu</i>e)</tt></p>
for write access.
<p><tt><i>key</i></tt> must always be of type \c string and a valid \ref Identifiers "identifier".
<p>Once again, in the following example a class for a point (this time a two-dimensional one) is used to represent a possible implementation.</p>
@code{.bpp}
class Point2d
{
private:
   double _x;
   double _y;
public:
   Point2d(double x=0, double y=0) { _x=x; _y=y; }
   double get_x() const { return _x; }
   void set_x(double val) { _x = val; }
   double get_y() const { return _y; }
   void set_y(double val) { _y = val; }
   double operator . (string key) const { return this->("get_"+key)(); }
   double operator .= (string key, double val) { 
      this->("set_"+key)(val); 
      return val;
   }
};

void main() {
   Point2d pt(15,25);
   pt.x *= 3;
   pt.y *= 2;
   print("pt: x=",pt.x," y=",pt.y,"\n");
}
@endcode
@note A custom dot operator does not override the default behavior of the operator for the class that defines it.<br> This means that the custom operator function will only be called if there is no member variable of the name specified by \c key that is visible in the current context.

@subsubsection DefIncDecOp Defining the Increment and Decrement Operators
<p>As alredy explained, the \ref IncDecOps "increment and decrement operators" can be used in prefix and postfix notation. Both variants can be defined for classes.</p>
<p>The operators are defined in the form</p>
<p><tt>    OP_INC()</tt> or <tt>OP_DEC()</tt> or<br>
<tt>    operator++()</tt> or <tt>operator--()</tt></p>
for prefix notation or
<p><tt>    OP_PINC()</tt> or <tt>OP_PDEC()</tt> or<br>
<tt>    operator++(var)</tt> or <tt>operator--(var)</tt> or<br>
<tt>    operator++(int)</tt> or <tt>operator--(int)</tt></p>
for postfix notation.
<p>Similar to C++ notation, the \c operator variant uses a dummy argument to distinguish between prefix and postfix notation.</p>
<p>The following example shows a portion of a rational number class to demonstrate the definition of the operators.</p>
@code{.bpp}
class Rational
{
private:
   int _num;    // numerator
   uint _denom; // denominator
public:
   Rational(int n=0, uint d=1) { _num=n; _denom=d; }
   Rational operator++() { _num += _denom; return this; }
   Rational operator++(int) {
      return new Rational(_num+_denom,_denom);
   }
   Rational operator--() { _num -= _denom; return this; }
   Rational operator--(int) {
      Rational r(_num,_denom);
      return --r;
   }
   operator string() { return newstring("%d/%u",_num,_denom); }
}

main()
{
   Rational r(1,2);
   print(r,"\n");             // prints 1/2
   print(r++," -> ", r,"\n"); // prints 1/2 -> 3/2
   print(++r,"\n");           // prints 5/2
}
@endcode
<p>The prefix notation implementations modify the object and return the modified object as the result.</p>
<p>The postfix notation implementations create a copy of the original object, modify it, and return it as the result.</p>
@note <ul>
<li>The implementation of the postfix variants is different from the usual C++ procedure! There you return a copy of the original object, in B++ the modified copy.</li>
<li>If a class defines only the prefix variant, this implementation is used implicitly when the operator is used in the postfix form, but not reverse. Although the compiler does not require it, prefix and postfix variants of the operators should generally be implemented in pairs to achieve behavior equivalent to that of the standard types.</li>
</ul>

@subsubsection DefAssignOp Defining the Assignment Operator
<p>For values of reference types, which also include objects, a reference to the target variable is normally simply assigned.</p>
<p>However, in certain cases it is desirable to be able to assign values of other types to an object, in addition to initialization in the constructor or as a reversal of conversion operators.<br>
Therefore, from version 1.8 onwards, the assignment operator can be redefined to behave similarly to C++.</p>
<p>The operator is defined in the form</p>
<p><tt>   <i>[returntype]</i> OP_ASSIGN(<i>[const] value</i>)</tt> or <br>
<tt>   <i>[returntype]</i> operator=(<i>const] value)</i>)</tt>,</p>
<p>where <tt><i>value</i></tt> is the value to be assigned, which may be preceded by a type specification.</p>
<p>If a user-defined assignment operator exists, it is called for every assignment to the object. It can then handle the assignment itself or, by returning the value null, activate the default handling (simple assignment to the target variable).</p>
@note <ul>
<li>Assigning the value <tt><i>null</i></tt>, or an object of the same or a derived type, is a special case. In this case, the user-defined assignment operator is not invoked. This exception is necessary to allow <tt><i>null</i></tt> to be assigned to the corresponding object variable, thereby releasing it or replacing an object instance.</li>
<li>A user-defined assignment operator should return either the object itself or the assigned value, in order to replicate the default behaviour of the assignment operator for simple data types (value types).</li>
</ul>


@subsubsection DefDerefOp Defining the Dereference Operator
The unary dereference operator <tt>*</tt> is primarily used to convert a weak reference into a "real" value (see \ref UnaryRefOps). In addition, it can be explicitly defined as a prefix operator for objects, as follows</p>
<p><tt>    <i>[const] [returntype]</i> OP_UNREF() <i>[const]</i></tt> or<br>
<tt>    <i>[const] [returntype]</i> operator*()<i>[const]</i></tt>.</p>
<p>The operator should be used to return an embedded object or other reference without modifying the defining object itself. A typical use case for this would be an iterator on a custom container that returns the object pointed to by the iterator.</p>

@subsubsection DefUnaryOps Defining other Unary Operators
<p>Table below lists the additional unary operators that can be defined for B++ classes.</p>
| Operator | Function | Operator Notation | Meaning |
| :------: | :------: | :---------------: | :-----: |
| \+ | <tt>OP_PLUS()</tt> | <tt>operator\+()</tt> | Positive sign |
| \- | <tt>OP_NEG()</tt> | <tt>operator\-()</tt> | Negative sign (two's complement) |
| ! | <tt>OP_NOT()</tt> | <tt>operator!()</tt> | Logical negation |
| ~ | <tt>OP_BNOT()</tt> | <tt>Operator~()</tt> | Binary negation (one's complement) |

<p>The implementation rules for these operators are largely the same as in C++. The corresponding operator function should leave the calling object unchanged and return a modified copy of that object.</p>
<p>An implementation of the negative sign for the Rational class from example \ref DefIncDecOp "above" might look like this:</p>
@code{.bpp}
Rational operator-() const { return new Rational(-_nom, _denom); }
@endcode
<p>The operator functions of unary operators always have an empty argument list. Optionally, a return type can be specified explicitly and operator function can be declared as \t const.</p>

@subsubsection DefCompOps Indirect definition of comparison operators using the methods \c compare and \c equals
<p>Unlike C++, B++ does not allow the direct definition of \ref CompOps "comparison operators". However, this is possible indirectly by using the member functions</p> 
<p><tt>    <i>[</i>bool<i>]</i>equals(<i>[typename] other</i>) <i>[</i>const<i>]</i></tt><br>
and/or<br>
<tt>    <i>[</i>int<i>]</i> compare(<i>[typename] other</i>) <i>[</i>const<i>]</i></tt></p>
<p>of a class where the types of arguments and return values are optional.</p>
<p>The \c equals method should return \c true if there is an equality between the calling object and <tt>\e other</tt>, otherwise return <tt>false</tt>.</p>
<p>The \c compare method should return a negative value if the calling object is less than other, a positive value if it is greater than other, and <tt>0</tt> on equality.</p>
<p>Methods should change neither the calling object nor the <tt>\e other</tt> object.</p>
<p>If an object is used in an expression as the left operand of a comparison operator, then in the case of the <tt>==</tt> and <tt>!=</tt> operators, the object is searched first for an \c equals method, for all other comparison operators, or if \c equals does not exist, for a \c compare method to perform the comparison sought.</p>
<p>If an object occurs as the right operand, the procedure is followed accordingly and the result of the comparison is reversed. If both operands are objects, the left operand "wins" if it implements suitable comparison methods. If neither operand provides its own comparison method, the standard comparison rules apply.</p>
<p>Following example extends the Rational class example \ref DefIncDecOp "above" by adding a \t compare method.</p>
@code{.bpp}
class Rational
{
   int _num; // numerator
   uint _denom; // denominator
   Rational(int n=0, uint d=1) { _num=n; _denom=d; }
   // other functions ...
   operator string() const { return newstring("%d/%u",_num,_denom); }
   operator double() const { return ::double(_num) / _denom; }
   int compare(const var other) const {
      double d = double() - ::double(other);
      return d > 0 ? 1 : d < 0 ? -1 : 0;
   }
}

main()
{
   Rational r(1,2);
   print (r<0,r>0,r==0,r!=0,0<r,0>=r); // prints 010110
}
@endcode
<p>The example also uses a type \ref DefTypeConvOps "conversion" to <tt>%double</tt>. Note that to prevent a recursive call to the member function <tt>%double</tt>, the global conversion function \c #double is explicitly called with the range resolution operator (<tt>::</tt>).</p>

@subsubsection DefInfixOps Defining Binary Infix Operators
<p>When defining the binary infix operators, note that the object (the operand) can be on the left or right side of the operator. Since operators in B++ are always defined as member functions, there are two functions for each operator (see Table below), with the right operand variant having the suffix <tt>_R</tt>.</p>
<p>In the \c operator notation, to distinguish the two forms between the keyword \c operator and the operator symbol, there is an \c L (object as left operand) or an \c R (object as right operand), although the \c L can also be omitted - the left variant is assumed by default.</p>
<table><tr><th valign="top" rowspan="2">Operator</th><th colspan="2">Function</th><th rowspan="2" valign="top">Operator notation</th></tr>
<tr><th>left</th><th>right</th></td></tr>
<tr><th colspan="4">Arithmetic operators</th></tr>
<tr><td align="center"><tt>+</tt></td><td><tt>OP_ADD(arg)</tt></td><td><tt>OP_ADD_R(arg)</tt></td><td><tt>operator [L|R] + (arg)</tt></td></tr>
<tr><td align="center"><tt>-</tt></td><td><tt>OP_SUB(arg)</tt></td><td><tt>OP_SUB_R(arg)</tt></td><td><tt>operator [L|R] - (arg)</tt></td></tr>
<tr><td align="center"><tt>*</tt></td><td><tt>OP_MUL(arg)</tt></td><td><tt>OP_MUL_R(arg)</tt></td><td><tt>operator [L|R] * (arg)</tt></td></tr>
<tr><td align="center"><tt>/</tt></td><td><tt>OP_DIV(arg)</tt></td><td><tt>OP_DIV_R(arg)</tt></td><td><tt>operator [L|R] / (arg)</tt></td></tr>
<tr><td align="center"><tt>\%</tt></td><td><tt>OP_REM(arg)</tt></td><td><tt>OP_REM_R(arg)</tt></td><td><tt>operator [L|R] \% (arg)</tt></td></tr>
<tr><th colspan="4">Bitwise operators</th></tr>
<tr><td align="center"><tt>\|</tt></td><td><tt>OP_BOR(arg)</tt></td><td><tt>OP_BOR_R(arg)</tt></td><td><tt>operator [L|R] \| (bad)</tt></td></tr>
<tr><td align="center"><tt>&</tt></td><td><tt>OP_BAND(arg)</tt></td><td><tt>OP_BAND_R(arg)</tt></td><td><tt>operator [L|R] & (arg)</tt></td></tr>
<tr><td align="center"><tt>^</tt></td><td><tt>OP_XOR(arg)</tt></td><td><tt>OP_XOR_R(arg)</tt></td><td><tt>operator [L|R] ^ (arg)</tt></td></tr>
<tr><th colspan="4">Shift operators</th></tr>
<tr><td align="center"><tt>&lt;&lt;</tt></td><td><tt>OP_SHL(arg)</tt></td><td><tt>OP_SHL_R(arg)</tt></td><td><tt>operator [L|R] &lt;&lt; (arg)</tt></td></tr>
<tr><td align="center"><tt>&gt;&gt;</tt></td><td><tt>OP_SHR(arg)</tt></td><td><tt>OP_SHR_R(arg)</tt></td><td><tt>operator [L|R] &gt;&gt; (arg)</tt></td></tr>
</table>
<p>The principle of definition is the same for all these operators and is illustrated in the following example for the addition operator.<br>
Here, the class \c Point (see \ref DefIndexOp) is modified and the + operator is implemented in such a way that it creates a new \c Point object, whose coordinates are formed as the sum of the coordinates of the operands, if the second operand is also of type \c Point. Otherwise, an attempt is made to convert the second operand to \c double type and add its value to all components of the first operand, with the result also being a new object.</p>
@code{.bpp}
class Point
{
   vector _coords;                              // vector of coordinates
   vector coords() const { return _coords };    // gets coordinates
   Point(uint dim);                             // ctor
   Point operator+(const var other) const;      // operator + (left)
   Point operator R +(const var other) const;   // operator + (right)
}

Point::Point(uint dim)
{
   _coords = newvector(dim);
   for (uint i=0; i<dim; ++i) _coords[i] = 0.0;
}

Point Point::operator+(const var other) const
{
   uint dim = size(_coords);
   if (dynamic_cast(Point, other))
   {
      vector ocoords =  other->coords();
      uint odim = size(ocoords);
      if (odim < dim) dim = odim;
      Point result(dim);
      vector rcoords = result->coords();
      for (uint i=0;i<dim;++i) rcoords[i] = _coords[i] + ocoords[i];
      return result;
   }
   double d = other;  // implicit conversion
   Point res(dim);
   vector rc = res->coords()
   for (uint j=0;j<dim;++j)
     rc[j] = _coords[j] + d;
   return res;
}

Point Point::operator R+(const var other) const
{
   return OP_ADD(other);
}
@endcode
@note <ul>
<li>To achieve behavior analogous to the built-in data types for user-defined classes, the infix operators should always be defined in pairs (i.e., for the left and right operands).</li>
<li>The operators should never modify one or both operands, but always return a new object. The type of the result should match the type of the defining object.</li>
<li>If the behavior of an operator is symmetrical, as in addition, the implementation of one variant can call that of the other one (see <tt>operator R+</tt> in example above). The functional form must be used for the call.</li>
<li>The type of the second operand passed as an argument is often (as in the example) not statically typed to allow use in mixed expressions. In such a case, the implementation of the operator function is responsible for performing appropriate type checking or conversions.</li>
<li>Infix operators are evaluated from left to right. That is, the type of the left operand is considered first. If it is an object type, then the corresponding left operator function, if any, is called with the right operand as an argument. If the right operand is an object but the left operand is not, then the right operator function is called with the left operand as an argument.</li>
</ul>
@subsubsection DefTypeConvOps Type Conversion Operators
<p>As already \ref TypeConversions "mentioned", member functions can be defined for objects (classes) to convert them into other data types.<br>
Syntactically, two variants are allowed:</p>
<pre><tt>    <i>[type] type</i>() <i>[</i>const<i>]</i></tt></pre>
or
<pre><tt>    operator <i>type</i>() <i>[</i>const<i>]</i>.</tt></pre>
<p>The first form is a 'normal' method definition, where the method name (<tt><i>type</i></tt>) corresponds to the return type. Optionally, the return type can also be specified. The second form is the C++ notation for conversion operators.</p>
<p>Conversion methods do not take arguments.</p>
The example in section about \ref DefCompOps "definition of comparison operators" defines conversion operators into the types \c double and \c string for the class \c Rational.</p>
<p>To explicitly convert values to object types, you can also use global functions that have the same name as the class whose type you want to convert, i.e., the form</p>
<pre><tt>    <i>[classtype] classtype</i>(<i>[const] [type]arg</i>)</tt></pre>
<p>Such a function should always return a result of the type of the corresponding class, or \c null if no conversion is possible. Otherwise, there are no strict implementation rules for such functions.</p>
@note Technically, a global conversion function is an "ordinary" function that can take any arguments, perform any actions, and return any results, and whose only special feature is that its name matches that of a class. It would also be conceivable to use such functions to create objects (instead of the \c new operator), i.e. in the role of factory functions.

@section Namespaces Namespaces
<p>The concept of namespaces, which is used to structure identifiers according to their intended use and to avoid identifier conflicts, is used in several programming languages, including C++ and Java.</p>
<p>Namespaces are supported in B++ since version 1.5 and are syntactically analogous to C++ and defined in the form</p>
<p><tt>    namespace <i>dentifier</i> { ... }</tt>.</p>
<p>From a technical point of view, namespaces in B++ are classes with the following restrictions.</p>
<ul>
<li>All members (variables, functions) are class members (\c static).</li>
<li>There are no constructors/destructors, so no instances can be created.</li>
<li>All members are implicitly \c public.</li>
<li>There is no inheritance of namespaces.</li>
</ul>
<p>Namespaces can contain child namespaces, class definitions, variables, and constants. However, they cannot be part of a real class; defining a namespace as a child of a class is not allowed (unlike real classes).</p>
<p>Referencing elements of a namespace is done like referencing static elements of a class, using the scope resolution operator (<tt>::</tt>).<br> There is <i>no</i> \t using clause, so <i>elements</i> of a namespace <i>must always be addressed explicitly</i>, except in the context of the namespace itself or a subordinate namespace.</li>

@section MemoryManagement Memory Management
<p>In Section \ref Datatypes a distinction was made between the data types occurring in B++ according to \ref ValueTypes "value types" and \ref ReferenceTypes "reference types".</p>
<p>Whereas a value type is directly bound to the existence of a value object, a reference type contains only a reference to a data area. This raises the question of how to manage the (dynamic) storage required for the actual data.</p>
<p>A special case is the type \c FILE, whose instances only contain a reference to a description structure provided by the operating system, which is requested or released by the standard functions #fopen and #fclose.</p>
<p>For all other reference types, B++ uses automatic memory management with reference counting by default. That is, each value of a reference type carries an internal reference count that is incremented when assigned to a variable and decremented when released (when the variable goes out of scope or is assigned a different value). When a reference counter reaches zero, it means that the value can no longer be accessed from anywhere in the program. In this case, it (and the memory used for the data area) is automatically freed.</p>
@note In contrast to many other scripting languages, B++ does not use a true garbage collector for reasons of runtime efficiency.
</p>This behavior means that the lifetime of variables is strictly defined in B++. In particular, it is guaranteed that when you exit a function or throw an \ref ExceptionHandling "exception", all temporary variables in the respective context are freed, and the destructors of objects are called implicitly.</p>
<p>The example below illustrates this:</p>
@code{.bpp}
class A {
   static uint _id = 0;
   uint id;
   A() { id = ++_id; print(__func__," id:",id,"\n"); }
   ~A() { print(__func__," id:",id,"\n"); }
   operator string() { return newstring("class: %s id: %u",
                              getclassname(this),id); }
}
void testfunc() {
     A a;
}
void testfunc2() {
    A a;
    throw new A();
}

main()
{
   try {
      print("enter testfunc\n");
      testfunc();
      print("enter testfunc2\n");
      testfunc2();
   }
   catch(e) {s
      print(e," caught\n");
   }
}
@endcode 
<p>Two functions (\c testfunc and \c testfunc2) are defined here, each of which creates an object of class \c A. While \c testfunc simply returns to the caller, \c testfunc2 throws an exception with another instance of class \c A as the exception object. In the main program, both functions are called in a protected section (<tt>try</tt>-<tt>catch</tt>), producing the following output:</p>
<pre><tt>enter testfunc
A::A id:1
A::dtor id:1
enter testfunc2
A::A id:2
A::A id:3
A::dtor id:2
Class: A id: 3 caught
A::dtor id:3</tt></pre>
<p>The object created in \c testfunc (ID=1) is released when the function is exited. In \c testfunc2, an object is first created locally (ID=2) and then another instance of \c A (ID=3) is created as an exception object. The automatic release of the local object (ID=2) now occurs when \c testfunc2 is exited (immediately after the exception is thrown), while the exception object (ID=3) is released when the \c catch block is exited.</p>
@note In the example, \c testfunc2 could also use the local object \c a (ID=2) directly as the exception object. In this case, when \c throw is called, its reference count would be incremented so that a release does not occur until the \c catch block in main is exited.</p>

@subsection WeakRefs Weak References and the Unary Operators & and *
<p>One problem with memory management using reference counting is the occurrence of <i>cyclic references</i>, as illustrated in figure below (top portion) using a double-linked list:</p>
@image html dbllist.png "Cyclic References and their Resolution"
@image rtf dbllist.png "Cyclic References and their Resolution"
<p>Because of the mutual references between the list elements, the reference counts of the elements are each two. If you release the reference to the beginning of the list (the variable \c first), the reference count of the first element is reduced, but does not reach zero, so that the element (or the entire list) is not released, even though there is no way to access it from the program.</p>
<p>This can be solved by using references that are explicitly excluded from the reference count (often called <i>weak references</i>), as shown in the bottom part of the figure.</p>
<p>In B++, such references are created with the unary operator <tt>&amp;</tt>, which excludes the trailing value from reference counting when it is subsequently assigned to a variable.</p>
<p>The unary operator <tt>*</tt> is its counterpart. It converts a weak reference back into a "real" reference, i.e., a variable to which the result is assigned is included in the reference count again. Following example demonstrates the practical use of weak references in more detail.</p>
@code{.bpp}
// List class example
// -----------------
// List element
class ListElement
{
private:
   var _prev = null;
   ListElement _next = null;
   var _value = null;
public:
   // ctor
   ListElement( var v = null; ) { _value = v; }
   // Define operator. for mamber access
   var operator.(string key) {
       switch (key)
       {
        case "prev": return _prev;
        case "next": return _next;
        case "value": return _value;
       }
       throw "invalid key " + key;
   }
   void operator.=(string key, var val) {
       switch (key)
       {
        case "prev":
          prev = &val; 
          break;
        case "next": 
           _next = val;
           break;
        case "value": 
           _value = val;
           break;
        default:
          throw "invalid key " + key;
      }
   }
}

// List iterator class
class List; 
class List_iterator {
private:
   var _lst = null;
   var _item = null;
public:
   // ctor
   List_iterator(List lst,var item = null) { _lst = &lst; _item = &item;}
   // Incremant
   List_iterator operator++() {
      if (_item) _item = &_item.next;
      else _item = &_lst.first();
      return this;
   }
   // Post-Increment
   List_iterator operator++(int) {
      List_iterator it(_lst,_item);
      return ++it;
   }
   // Decrement
   List_iterator operator--() {
      if (_item) _item = &_item.prev;
      else _item = &_lst.last();
      return this;
   }
   // Post-Decrement
   List_iterator operator--(int) {
      List_iterator it(_lst,_item);
      return --it;
   }
   var item() { return _item; }
   var lst() { 
     return _lst; 
   }
   // Equality operators
   bool equals(List_iterator other) {
       if (_lst != other->(List_iterator::lst)()) return false;
       return _item == other->(List_iterator::item)(); 
   }
   // Gets referenced list item.
   ListElement operator*() { return *_item; }
   // Delegates operator. to referenced list element
   var operator.(string key) { return _item->(ListElement::OP_PREF)(key); }
   void operator.=(string key, var val) { 
     _item->(ListElement::OP_PSET)(key,val); 
   }
}

// List class
class List
{
private:
    ListElement _first = null;
    var _last = null;
    uint _size = 0;
    // Internal helpers (protected methods)
    // Initialization
    void _init (var first, var last, uint siz) {
       _first = first; _last = last; _size = siz;
    }
    // Removes an element.
    ListElement _remove(var el) {
       if (!_size) throw "List is empty";
       if (!el) throw "Invalid argument";
       if (!el.prev) {
            var f = _first;
           _first = el.next;
       }
       else {
           var e = el.prev.next;
           el.prev.next = el.next;
       }
       if (!el.next) _last = el.prev;
       else el.next.prev = el.prev;
       --_size;
       return el.next;
     }
     // Inserts an element
     ListElement _insert(var val, var beforeEl) {
        ListElement el(val);
        if (!beforeEl) {
          if (_last) {
             el.prev = _last;
             _last.next = el;
          }
            else _first = el;
            _last = &el;
        }
        else {
           if (!_size) throw "List is empty";
           el.next = beforeEl;
           if (!beforeEl.prev) _first = el;
           else {
              beforeEl.prev.next = el;
              el.prev = beforeEl.prev;
           }
           beforeEl.prev = &el;
        }
        ++_size;
        return el;
     }
public:
    // Ctor - allows initialization from vectoe
    List( vector init = null) {
        if (init) {
            uint n = size(init);
            for (uint i=0;i<n;++i) this->(_insert)(init[i],null); 
        }
    }
    // STL-like functions
    ListElement front() { return _first; }
    ListElement back() { return _last ? *_last : null; } 
    List_iterator begin() { return new List_iterator(this,_first); }
    List_iterator end() { return new List_iterator(this); }
    void push_back(var val) { this->(_insert)(val); }
    void push_front(var val) { this->(_insert)(val,_first); }
    void pop_back() { this->(_remove)(_last); }
    void pop_front() { this->(_remove)(_first); }
    List_iterator insert(List_iterator before,var val) {
       if (before->(List_iterator::lst)() != this) throw "Invalid iterator";
       return this->(_insert)(val,before->(List_iterator::item)());
    }
    List_iterator erase(List_iterator first, List_iterator last = null) {
       if (first->(List_iterator::lst)() != this) throw "Invalid iterator";
       if (!last) 
          return new List_iterator(this,this->(_remove)(
            first->(List_iterator::item)()));
       if (last->(List_iterator::lst)() != this) throw "Invalid iterator";
       var item = first->(List_iterator::item)();
       var litem = last->(List_iterator::item)();
       while (item) {
         bool end = item == litem;
         item = &this->(_remove)(item);
         if (end) break;
       }
       return new List_iterator(this,item);
    }
    uint size() { return _size; }
    void clear() { _first = null; _last = null; _size = 0; }
    void swap(List other)
    {
       var ofirst = other->(List::front)();
       var olast = other->(List::back)();
       uint osize = other->(List::size)();
       other->(List::_init)(_first,_last,_size);
       _first = ofirst; _last = &olast; _size = osize;
    }
    // Conversion to string
    operator string() {
       string result="";
       for (var el = _first; el; el = el.next)
       {
          result += ::string(el.value);
          if (el.next) result += ",";
       }
       return result;
    }
}

main()
{
     List l([1,2,3,4,5,6,7]);
     List l2([9,8,7,6]);
     l->insert(l->end(),"00"); // appends "00" to l
     auto i = l->begin();
     ++i;
     auto j = clone(i);
     ++j;
     l->erase(i,++j); // removes second and third element from l
     for (auto it = l->(List::begin)();it != l->(List::end)();++it)
        print(*it.value,"\n"); // prints contents of l
     for (it = l2->(List::begin)();it != l2->(List::end)();++it)
        print(*it.value,"\n"); // prints contents of l2
     print(l,"\n",l2,"\n"); // prints l and l2 using string conversion
     print("--------------\n");
     l->swap(l2); // exchanges contents of l and l2
     for (it = l->(List::begin)();it != l->(List::end)();++it) 
        print(*it.value,"\n");
     for (it = l2->(List::begin)();it != l2->(List::end)();++it)
        print(*it.value,"\n");
     print(l,"\n",l2,"\n");
}
@endcode
<p>A double-linked list is implemented here, similar to that in the C++ standard library.<br>
The example also illustrates some of the object-oriented programming techniques described \ref ObjectProg "above", in particular the definition of \ref OperatorDefinition "user-defined operators" and the \ref ExtendedCallSyntax "static (not virtual) binding" of member functions.</p>

@subsection ExplicitMem Explicit Memory Management
In addition to creating \ref WeakRefs "weak references" to resolve circular references, the unary <tt>&amp;</tt> operator can also be used to create variables or objects (more precisely: values that are actually subject to reference counting) that are excluded from reference counting and therefore must be explicitly freed using the \c delete operator.<br>
This can be useful in exceptional cases where the destruction of a particular object should occur at a precisely specified time, i.e. before the implicit destruction when the variable holding the value leaves the scope. This is especially true for global (or \c static) variables, which are normally destroyed only when the B++ VM is released, which may prevent destructors of objects from being called.</p>
</p>An explicitly managed variable is created by converting a value of a reference type into a weak reference the first time it is assigned to the variable, e.g:</p>
@code{.bpp}
var obj = &new MyClass();
var vec = &newvector(1,2,3);
@endcode
<p>When variables initialized in this way are no longer needed, they must be released using the \c delete operator:</p>
@code{.bpp}
delete obj;
delete vec;
@endcode
or better
@code{.bpp}
obj = delete obj;
vec = delete vec;
@endcode
<p>Unlike C++, the B++ delete operator always returns the value \c null, which can be reassigned to the variable to prevent later accidental use of the now invalid object reference.</p>

@note <ul>
<li>Like all weak references, explicitly managed values cannot be used with static typing.</li>
<li>It is possible to subsequently convert the value of an originally explicitly managed variable to an automatically managed value by using the dereference operator <tt>*</tt> and assigning it to another variable, but the reverse is not true.<br>
<b>Caution:</b> Such a dereference results in the immediate release of the object (analogous to calling delete) if there is no assignment to a variable made.</li>
</ul>

*/