Created
July 2, 2019 10:14
-
-
Save dunkfordyce/31d4a14c319891337aa6987783c0c1e4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// classes example | |
#include <iostream> | |
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())); | |
} | |
}; | |
int main () { | |
try { | |
Object* a = Int::create(2); | |
Object* b = String::create("hello"); | |
Object* c = Int::create(5); | |
Object* d = a->add(c); | |
cout << "a->toString() " << a->toString() << '\n'; | |
cout << "b->toString() " << b->toString() << '\n'; | |
cout << "c->toString() " << c->toString() << '\n'; | |
cout << "d->toString() " << d->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