Skip to content

Instantly share code, notes, and snippets.

@prespondek
Last active August 29, 2015 14:13
Show Gist options
  • Save prespondek/2793fe441c731d13ff56 to your computer and use it in GitHub Desktop.
Save prespondek/2793fe441c731d13ff56 to your computer and use it in GitHub Desktop.
C++ Demo
/****** CPlusPlus.h ******/
#include "somelib.h"
class MyClass; // forward declaration
// c++ has multiple inhereitance so no need for protocol.
class MyProtocol
{
public:
// pure virtual function
virtual bool protocolFunction() = 0;
};
class MyClass : public MyProtocol
{
protected:
int _protected_value; // member values are protected by default
std::function<void(float)> _callback; // function pointer.
public:
int _public_value; // public variable
protected:
std::string _property_string; // no properties in c++ so we must declare our getters and setters manually
public:
std::string& getPropertyString (); // getter
void setPropertyString(std::string& str); // setter
static MyClass* sharedInstance (); // static function
MyClass(); // constructor
~MyClass(); // destructor
void classFunction (std::string& name, const std::function<void(float)>& callback);
bool protocolFunction(); // need to declare pure virtual functions in c++
};
/****** CPlusPlus.cpp ******/
static MyClass* instance = nullptr;
MyClass* MyClass::sharedInstance ()
{
if (instance == nullptr) {
instance = new MyClass();
}
return instance;
}
// constructor
MyClass::MyClass() :
_protected_value(1),
_public_value(2)
{
}
// destructor
MyClass::~MyClass()
{
}
void MyClass::classFunction (std::string& name, const std::function<void(float)>& callback)
{
_callback = callback;
}
bool MyClass::protocolFunction()
{
bool val = true;
return val;
}
/****** main.cpp ******/
int main(int argc, const char * argv[])
{
MyClass* test = MyClass::sharedInstance();
std::string name = "some text";
test->classFunction(name, [=] (float dt) { // lamdba function. [=] captures a copy of function variables.
//do something
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment