Polyglot CheatSheet - Class

Updated: 2021-11-19
  • there is no way to write a Java program without a class.
  • rust does not have the keyword class, instead it is achieved by struct + impl.

Constructor / Destructor

C++

class Foo {
 public:
  Foo(const Foo& arg);             // copy constructor
  Foo(Foo&& arg);                  // move constructor
  Foo& operator=(const Foo& rhs);  // copy assignment operator
  Foo& operator=(Foo&& rhs);       // move assignment operator

  ~Foo(); // destructor
}

Rust

Constructor:

struct Foo {
  my_field: isize
}

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

Destructor:

fn drop(&mut self);

Java

public class Foo {
  private final int myField;

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

Methods

Rust

struct doesn’t support methods, use the impl keyword