Skip to content

Instantly share code, notes, and snippets.

@techtonik
Last active May 21, 2016 07:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save techtonik/ce85e2e5e1773e02f91cb8e1156d049a to your computer and use it in GitHub Desktop.
Save techtonik/ce85e2e5e1773e02f91cb8e1156d049a to your computer and use it in GitHub Desktop.
Driver inheritance pattern - parent should print child's name

See getname.py and try to implement the same in C++ with and without using templates.

$ python getname.py 
Unknown
Specific

$ g++ -std=c++14 -O2 -Wall -pedantic main.cpp && ./a.out
Unknown
Specific
#include <iostream>
#include <string>
class Driver {
public:
std::string name = "Unknown";
void init() {
std::cout << name << std::endl;
}
};
// need public here to inherit init()
class SpecificDriver : public Driver {
public:
std::string name = "Specific";
};
int main() {
Driver d;
SpecificDriver sd;
// this gives Unknown Unknown =/
d.init();
sd.init();
}
"""
This Python code contains two driver classes - parent constructor prints
name of current driver. This is an example that should be ported to C++.
Code is placed into public domain.
"""
class Driver(object):
name = "Unknown"
def __init__(self):
print(self.name)
class SpecificDriver(Driver):
name = "Specific"
def __init__(self):
super(SpecificDriver, self).__init__()
Driver()
SpecificDriver()
"""
This prints two strings to console
Unknown
Specific
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment