Skip to content

Instantly share code, notes, and snippets.

@dunkfordyce
Created July 2, 2019 13:59
Show Gist options
  • Save dunkfordyce/769a4a1e02b47c1b8ee00a88000562ae to your computer and use it in GitHub Desktop.
Save dunkfordyce/769a4a1e02b47c1b8ee00a88000562ae to your computer and use it in GitHub Desktop.
// classes example
// g++ -static-libgcc -static-libstdc++ main.cpp -o main.exe
#include <iostream>
#include <map>
using namespace std;
class Object {
public:
virtual string toString()=0;
virtual int toInt()=0;
virtual Object* add(Object* other)=0;
};
class Int : public Object {
int val;
public:
static Int* create(int val) {
Int *ret = new Int(val);
return ret;
}
Int(int in_val) {
val = in_val;
}
string toString() {
return std::to_string(val);
}
int toInt() {
return val;
}
Object* add(Object* other) {
int other_val = other->toInt();
return new Int(this->val + other_val);
}
};
class String : public Object {
string val;
public:
static String* create(string val) {
String* ret = new String(val);
return ret;
}
String(string in_val) {
val = in_val;
}
string toString() {
return val;
}
int toInt() {
throw "cant cast string to int";
}
Object* add(Object* other) {
return new String(val + (other->toString()));
}
};
class Stack {
std::map<string,Object*> objects;
Stack* parent = NULL;
public:
~Stack() {
std::map<string, Object*>::iterator it = objects.begin();
while (it != objects.end())
{
cout << "freeing " << it->first << '\n';
Object* object = it->second;
delete object;
it++;
}
}
Object* set(string name, Object* object) {
if( objects.count(name) > 0) {
delete objects[name];
}
objects[name] = object;
return object;
}
Object* get(string name) {
if( objects.count(name) == 0) {
if( parent != NULL ) {
return parent->get(name);
} else {
throw "no such object " + name;
}
}
return objects[name];
}
};
int main () {
try {
// Object* a = Int::create(2);
// Object* b = String::create("hello");
// Object* c = Int::create(5);
// Object* d = a->add(c);
// Object* e = b->add(a)->add(c)->add(d);
// cout << "a->toString() " << a->toString() << '\n';
// cout << "b->toString() " << b->toString() << '\n';
// cout << "c->toString() " << c->toString() << '\n';
// cout << "d->toString() " << d->toString() << '\n';
// cout << "e->toString() " << e->toString() << '\n';
Stack stack;
stack.set("i", Int::create(2));
stack.set("2", Int::create(1));
cout << "result " << stack.get("i")->add(stack.get("2"))->toString() << '\n';
} catch (const char *msg) {
cout << "errored with " << msg;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment