Skip to content

Instantly share code, notes, and snippets.

@stangirala
Last active December 21, 2015 07:28
Show Gist options
  • Save stangirala/6271215 to your computer and use it in GitHub Desktop.
Save stangirala/6271215 to your computer and use it in GitHub Desktop.
Example for a templated class data member that is "virtual". The virtual function that wraps around the data member, gets it to behave as a virtual data member.
#include <iostream>
using namespace::std;
template<typename A>
class base {
protected:
A data;
public:
virtual void set_value (A value) { data = value; }
virtual A return_data() = 0;
virtual void print() = 0;
};
template<typename A>
class derived : public base<A> {
float a;
public:
void set_value(A value) { this->data = value; }
A return_data() { return this->data;}
void print() { cout << "Print derived a value " << a << endl; }
};
int main() {
base<int> *obj = new derived<int>();
obj->set_value(10);
int b = obj->return_data();
cout << "b value " << b << endl;
obj->print();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment