Classes & Structs

Representations of complex data types with methods that operate on them.

C++

Rust

Java


class MyClass {
private:
  const int my_field;

public:
  // constructor
  MyClass(const int &field) : my_field(filed) { }

  // destructor
  ~MyClass() { }

  // friend functions
  ostream& operator<<(ostream &out, const MyClass &my_class) {
    out << my_field;
  }
}


struct MyClass {
  my_field: isize
}

impl MyClass {
  // constructor, by convention
  pub fn new(field: isize) -> MyClass {
    MyClass { my_field: field }
  }
}

impl Drop for MyClass {
  // destructor
  fn drop(&mut self) {
  }
}


public class MyClass {
  private final int myField;

  // constructor
  public MyClass(final int field) {
    this.myField = field;
  }

  // destructor
  finally { }

  // Java doesn't have friend functions
}



C++ and Java classes (or structs for C++) are both fairly similar. Rust is quite different though. A struct defines the fields, and an implementation defines the methods for the struct.