Skip to content

Instantly share code, notes, and snippets.

@melvyniandrag
Created April 5, 2017 19:56
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 melvyniandrag/e52c519ab42a2add605c8e22ca9711fe to your computer and use it in GitHub Desktop.
Save melvyniandrag/e52c519ab42a2add605c8e22ca9711fe to your computer and use it in GitHub Desktop.
#ifndef BASE_H
#define BASE_H
#include <map>
#include <string>
#include <iostream>
class Base{
public:
const std::map<std::string, std::string>& m;
Base(const std::map<std::string, std::string>& m_): m(m_){}
void printHelloStatement()
{
std::cout << "Hello " << m.at("Hello") << "!" << std::endl;
}
};
#endif
#include <map>
#include <string>
#include "Base.h"
#include "Derived.h"
const std::map<std::string, std::string> Derived::myM {
std::make_pair(std::string{"Hello"}, std::string{"World"})
};
#ifndef DERIVED_H
#define DERIVED_H
#include <map>
#include <string>
#include "Base.h"
class Derived: public Base{
public:
Derived(): Base(myM){}
static const std::map<std::string, std::string> myM;
};
#endif
#include <map>
#include <string>
#include "Base.h"
#include "Derived2.h"
const std::map<std::string, std::string> Derived2::myM {
std::make_pair(std::string{"Hello"}, std::string{"Kitty"})
};
#ifndef DERIVED2_H
#define DERIVED2_H
#include <map>
#include <string>
#include "Base.h"
class Derived2: public Base{
public:
Derived2(): Base(myM){}
static const std::map<std::string, std::string> myM;
};
#endif
#include <iostream>
#include "Base.h"
#include "Derived.h"
#include "Derived2.h"
int main(int argc, char** argv){
Derived d;
Derived2 d2;
d.printHelloStatement();
d2.printHelloStatement();
}
@melvyniandrag
Copy link
Author

All derived classes need to have a common functionality, i.e. to print some "Hello" statement. This common functionality depends on a map data structure. Unfortunately, each derived class needs a different map. And, because all derived objects of the same type need the same map, it can be static. And because it's static, the base class can just take a constant reference to it so that every instance doesn't have a copy and waste space.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment