The following code represents the strategy design pattern.
Consider the following program structure:
//base.hpp
#ifndef BASE_HPP
#define BASE_HPP
class Base {
public:
virtual ~Base() {};
virtual int solve() = 0;
};
#endif
//derived.hpp
#include "base.hpp"
class Derived: public Base {
public:
virtual int solve() { return 77; }
};
I have a client.cpp which receives a context of Derived
#include "client.hpp"
#include <iostream>
void Client::operate() {
std::cout << solver_.solve() << std::endl;
}
This is the header file of client:
#include "base.hpp"
class Client {
public:
Client(Base& b): solver_(b) {}
void operate();
private:
Base& solver_;
};
My main: test.cpp
#include "client.hpp"
#include "derived.hpp"
int main() {
Derived d;
Client c(d);
c.operate() ;
}
I would expect it to print 77, but the program doesn't print anything at all.
Client receives a context to Derived by it's constructor and stores it as Base& solver_; First, the operate method of Client is called, which calls the appropriate solve method of class that derives from Base. In this case, Derived.
Right, that should output 77, but it doesn't. The program compiles fine and no errors, just clean exit. Any ideas ?
I compiled it using following command:
g++ -o program.exe client.cpp test.cpp
I'm using GCC version 5.3.0