Skip to content

Instantly share code, notes, and snippets.

@ohmree
Created June 30, 2020 11:57
Show Gist options
  • Save ohmree/8176098f780f05a32385a228cbf5393d to your computer and use it in GitHub Desktop.
Save ohmree/8176098f780f05a32385a228cbf5393d to your computer and use it in GitHub Desktop.

Rust:

trait Interface {
    fn variable_we_need(&self) -> i32;
    fn use_variable() {
        do_something_with(self.variable_we_need());
    }
}

struct Implementer {
    variable_we_need: i32,
}

impl Implementer {
    pub fn new(variable_we_need: i32) {
        Self { variable_we_need }
    }
}

impl Interface for Implementer {
    fn variable_we_need(&self) {
        self.variable_we_need
    }
}

// Usage:
fn main() {
    let i = Implementer::new(5);
    i.use_variable();
}

C++:

class Interface {
public:
    Interface(int n) : variable_we_need(n) {};
    void use_variable() {
        do_something_with(variable_we_need);
    }
    // Mark this class as an abstract class or an interface.
    // In C++ it's a design pattern and not a language feature.
    virtual ~Interface() = default;

private:
    int variable_we_need;
}

class Implementer : public Interface {
    // Forward the arguments to the superclass constructor
    Implementer(int n) : Interface(n) {};
    // And that's it
}

int main() {
    Implementer i(5);
    i.use_variable();

    return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment