Skip to content

Instantly share code, notes, and snippets.

@Hydrotoast
Last active December 14, 2015 07:08
Show Gist options
  • Save Hydrotoast/5047846 to your computer and use it in GitHub Desktop.
Save Hydrotoast/5047846 to your computer and use it in GitHub Desktop.
#ifndef BASECLASS_H
#define BASECLASS_H
#include <string>
#include <iostream>
template <class Derived>
class BaseClass
{
public:
BaseClass(int i, const std::string& s): ii(i), ss(s) { }
// virtual ~BaseClass() { }
int getII() const { return ii; }
std::string getSS() const { return ss; }
// Returns a clone of the derived
Derived* clone() const { return new Derived(static_cast<const Derived&>(*this)); }
// print() is now statically polymorphic by calling the statically implemented derivedPrint()
void print(std::ostream& out) const { return static_cast<Derived&>(*this).derivedPrint(out); }
private:
// default handler for print
void derivedPrint(std::ostream& out) const {
out << "printing from base class!" << std::endl;
}
int ii;
std::string ss;
};
#endif // BASECLASS_H
#include "BaseClass.h"
class DerivedClass2 : public BaseClass<DerivedClass2>
{
public:
DerivedClass2(int i, const std::string& s, double d): BaseClass(i, s), dd(d) { }
// virtual ~DerivedClass2() { }
double getDD() const { return dd; }
private:
void derivedPrint(std::ostream& out) const {
out << "printing from DerivedClass2" << std::endl;
}
double dd;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment