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 | |
| """ |