Using a Wrapper for memory management in c++ - c++

Could anyone tell me why i get a compiling error in the "setFlyBehaviour" and "setQuackBehaviour" of the Duck class? (error : "term does not evaluate to a function taking 1 arguments")
this is an example of a strategy pattern from Head First Design Patterns (which is in Java that i translated here in C++). I introduced a Wrapper pattern in order to manage memory. (the wrapper class i'm using is from Mark Joshi, Option Pricing and Design Patterns)
Thanks!!!!!
#include <iostream>
#include <algorithm>
#include <math.h>
#include <string>
#include <map>
#include <exception>
#include <vector>
using namespace std;
template< class T>
class Wrapper
{
//Taken From Mark Joshi, Designs patterns and derivatives pricing
public:
Wrapper()
{ DataPtr =0;}
Wrapper(const T& inner)
{
DataPtr = inner.clone();
}
Wrapper(const Wrapper<T>& original)
{
if (original.DataPtr !=0)
DataPtr = original.DataPtr->clone();
else
DataPtr=0;
}
~Wrapper()
{
if (DataPtr !=0)
delete DataPtr;
}
Wrapper& operator=(const Wrapper<T>& original)
{
if (this != &original)
{
if (DataPtr!=0)
delete DataPtr;
DataPtr = (original.DataPtr !=0) ? original.DataPtr->clone() : 0;
}
return *this;
}
T& operator*()
{
return *DataPtr;
}
const T& operator*() const
{
return *DataPtr;
}
const T* const operator->() const
{
return DataPtr;
}
T* operator->()
{
return DataPtr;
}
private:
T* DataPtr;
};
/*****************************************************/
/***************** Interfaces ****************/
/*****************************************************/
class FlyBehaviour
{
private:
public:
virtual void fly() const = 0;
virtual FlyBehaviour* clone() const = 0;
};
class QuackBehaviour
{
private:
public:
virtual void quack() const = 0;
virtual QuackBehaviour* clone() const = 0;
};
/*****************************************************/
/***************** Implementations ***********/
/*****************************************************/
// -- FlyBehaviour
class FlyWithWings : public FlyBehaviour
{
public:
virtual void fly() const{
cout << "flying with wings" << endl;
}
virtual FlyBehaviour* clone() const {
return new FlyWithWings;
}
};
class FlyNoWay : public FlyBehaviour
{
public:
virtual void fly() const{
cout << "flying no way" << endl;
}
virtual FlyBehaviour* clone() const {
return new FlyNoWay;
}
};
// -- QuackBehaviour
class Quack : public QuackBehaviour
{
public:
virtual void quack() const{
cout << "Quacking here!" << endl;
}
virtual QuackBehaviour* clone() const{
return new Quack;
}
};
class Squeak : public QuackBehaviour
{
public:
virtual void quack() const{
cout << "Squeaking here!" << endl;
}
virtual QuackBehaviour* clone() const{
return new Squeak;
}
};
class Duck
{
private:
Wrapper<FlyBehaviour> flyBehaviour;
Wrapper<QuackBehaviour> quackBehaviour;
public:
void performQuack() const{
quackBehaviour->quack();
}
void performFly() const{
flyBehaviour->fly();
}
void setFlyBehaviour(const FlyBehaviour& mfly){
flyBehaviour(mfly);
}
void setQuackBehaviour(const FlyBehaviour& mquack){
quackBehaviour(mquack);
}
virtual void display() const{
}
};
class MallardDuck : public Duck
{
public:
virtual void display() const{
cout << "It looks like a Mallar" << endl;
}
};
class RedheadDuck : public Duck
{
public:
virtual void display() const{
cout << "It looks like a Redhead" << endl;
}
};
int main()
{
}

You were actually trying to call non-existent function instead of constructor.
There was also mistake in argument you were passing to setQuackBehaviour.
This should work:
void setFlyBehaviour(const FlyBehaviour& mfly){
flyBehaviour = mfly;
}
void setQuackBehaviour(const QuackBehaviour& mquack){
quackBehaviour = mquack;
}

It fails because Wrapper does not provide function call operator:
R T::operator ()(Arg1 a1, Arg2 a2, …)
And you are trying to make a call to Wrapper template:
flyBehaviour(mfly);

#werewindle like this ?
void reset(const QuackBehaviour& original){
if (DataPtr!= &original)
{
if (DataPtr!=0)
delete DataPtr;
DataPtr = (original.DataPtr !=0) ? original.DataPtr->clone() : 0;
}
}

Related

Using the dynamic_cast operator

I'm trying to understand dynamic type casting.
How to properly implement the DrawAnimals and Talk To Animals functions using dynamic_cast?
DrawAnimals draws animals that can be drawn. Such animals implement the Drawable interface.
TalkToAnimals conducts a conversation with animals that can talk, that is, they implement the Speakable interface.
class Speakable {
public:
virtual ~Speakable() = default;
virtual void Speak(ostream& out) const = 0;
};
class Drawable {
public:
virtual ~Drawable() = default;
virtual void Draw(ostream& out) const = 0;
};
class Animal {
public:
virtual ~Animal() = default;
void Eat(string_view food) {
cout << GetType() << " is eating "sv << food << endl;
++energy_;
}
virtual string GetType() const = 0;
private:
int energy_ = 100;
};
class Bug : public Animal, public Drawable {
public:
string GetType() const override {
return "bug"s;
}
void Draw(ostream& out) const override {
out << "(-0_0-)"sv << endl;
}
};
class Cat : public Animal, public Speakable, public Drawable {
public:
void Speak(ostream& out) const override {
out << "Meow-meow"sv << endl;
}
void Draw(ostream& out) const override {
out << "(^w^)"sv << endl;
}
string GetType() const override {
return "cat"s;
}
};
void DrawAnimals(const std::vector<const Animal*>& animals, ostream& out) {
/*if (const Animal* r = dynamic_cast<const Animal*>(&animals)) {
} else if (const Bug* c = dynamic_cast<const Bug*>(&animals)) {
}*/
}
void TalkToAnimals(const std::vector<const Animal*> animals, ostream& out) {
//?
}
void PlayWithAnimals(const std::vector<const Animal*> animals, ostream& out) {
TalkToAnimals(animals, out);
DrawAnimals(animals, out);
}
int main() {
Cat cat;
Bug bug;
vector<const Animal*> animals{&cat, &bug};
PlayWithAnimals(animals, cerr);
}
I am going to explain for DrawAnimals and you can extended to other functions by yourself.
What you did here:
void DrawAnimals(const std::vector<const Animal*>& animals, ostream& out) {
/*if (const Animal* r = dynamic_cast<const Animal*>(&animals)) {
} else if (const Bug* c = dynamic_cast<const Bug*>(&animals)) {
}*/
}
Is plain wrong for several reasons:
animals is a vector
If you intended an individual element, then because &animals[i] (i = [0..animals.size()]) is a pointer to pointer (Animal**)
Because dynamic_cast<const Animal*>(animals[i]) (i = [0..animals.size()]) is the identity.
You need to work with each individual element of the vector:
void DrawAnimals(const std::vector<const Animal*>& animals, ostream& out) {
for (auto animal : animals) {
if (const Drawable* r = dynamic_cast<const Drawable*>(animal)) {
// this animal is Drawable
} else if (const Bug* c = dynamic_cast<const Bug*>(animal)) {
// this animal is a Bug
// only issue here: Bugs are also Drawable
// so this code will never be reached
}
}
}
Question: Why are some animals Drawable and other don't?

C++ imitating properties from C#

I really miss get/set in C++, so I'm trying to do something similar. This is what I have now:
#pragma once
#define Property(T) class : public property<T>
#define Get(T) T* get() override
#define Set(T) T* set(T* _value) override
#define MutableProperty(T) using property<T>::operator=
#include <ostream>
template<typename T>
class property
{
protected:
T* value;
virtual T* get() = 0;
virtual T* set(T* _value) = 0;
public:
property()
{
value = NULL;
}
~property()
{
delete value;
}
T* operator=(T* _value)
{
return set(_value);
}
T* operator=(T _value)
{
return set(new T(_value));
}
operator T*()
{
return get();
}
friend std::ostream& operator<<(std::ostream& out, property& prop)
{
return out << *prop.get();
}
};
and this works like this:
#include "Property.h"
Property(string)
{
Get(string)
{
return value;
}
Set(string)
{
return value = _value;
}
public:
MutableProperty(string);
} strprop;
int main()
{
strprop = "teststring";
cout << strprop;
getchar();
return 0;
}
which I already like how it looks, but is there any trick of getting rid of those Get(type) Set(type)?
Also, is this actually good approach or this is poor code?

How should i overload += operator in a vector template?

I got a template class Atlas that will store objects of Animal class and derived classes of Animal;
here's the code:
#include <iostream>
#include <assert.h>
#include <list>
using namespace std;
class Animal {
protected:
std::string m_name;
Animal (std::string name): m_name {name} {}
public:
virtual std::string regn() const { return "???"; }
virtual ~Animal(){
cout << "Destructor animal"<<'\n';}
};
class Nevertebrate : public Animal{
public:
virtual std::string regn() const { return "nevertebrate";}
virtual ~Nevertebrate();
};
class Vertebrate: public Animal {
protected:
/* std::string m_name;
Vertebrate (std::string name)
:m_name {name} {} */
Vertebrate (std::string name)
: Animal {name} {}
public:
virtual std::string regn() const { return "vertebrate";}
virtual ~Vertebrate(){
cout<<"Destructor vertebrate"<<'\n';};
};
class bird: public Vertebrate {
public:
bird(std::string name)
: Vertebrate{ name }{}
void set_name (std::string nume){
m_name = nume;}
std::string get_name(){
return m_name;}
virtual std::string regn() const {return "pasare";}
virtual ~bird (){
cout << "destructor bird"<<'\n';}
};
template <class T>
class Atlas
{
private:
int m_length{};
T* m_data{};
public:
void SetLength(int j);
Atlas(int length)
{
assert(length > 0);
m_data = new T[length]{};
m_length = length;
}
Atlas(const Atlas&) = delete;
Atlas& operator=(const Atlas&) = delete;
~Atlas()
{
delete[] m_data;
}
void erase()
{
delete[] m_data;
m_data = nullptr;
m_length = 0;
}
T& operator[](int index)
{
assert(index >= 0 && index < m_length);
return m_data[index];
}
int getLength() const;
};
template <class T>
int Atlas<T>::getLength() const
{
return m_length;
}
template <class T>
void Atlas<T>::SetLength(int j){m_length = j;
}
int main()
{
Atlas<Bird> AtlasBird(10);
Bird b;
AtlasBird.SetLength(11);
AtlasBird[10] = b --- it gets a memoryleak from here.
return 0;
}
I want to overload the += operator so that i can insert a new object into my Atlas, (e.g. AtlasAnimal).
I tried with the SetLength function to increase the length, (e.g. AtlasAnimal.SetLength(11)) but when i try to assign AtlasAnimal[10] an object (e.g. Bird b) it drops a memory leak.
I'm sorry if there was a similar question answered, but i couldn't find anything that helps

Calling thread on member function

Sorry for the long example, but the question is simple. I'm using basic Visitor Pattern, with a mediator to manage several concrete Visitor_pick : public DataVisitor objects. The conrete mediator, SimulatorMediator, fills a list with Visitor_pick objects, then wants to call std::thread on a DataVisitor member function. I have tried several variants, using mem_fun1_t<>, etc., with no luck. Can't compile. What is the correct syntax?
The call in question should be at line 205 - I'd like to attach threads to v->visit_SpreadData, a unary function, then populate threadVec. Any help would be appreciated.
#include <iostream>
#include <ostream>
#include <iterator>
#include <list>
#include <vector>
#include <algorithm>
#include <thread>
class PublishEvent;
class Subscriber
{
public:
virtual void update(const PublishEvent *e) = 0;
~Subscriber() = default;
};
class Publisher
{
public:
void attach(Subscriber*);
void detach(Subscriber*);
void notify(const PublishEvent*);
protected:
std::list<Subscriber*> subscribers_;
};
inline void Publisher::
notify(const PublishEvent *e)
{
for (auto &s : subscribers_)
s->update(e);
}
inline void Publisher::
attach(Subscriber *s)
{
subscribers_.push_back(s);
}
inline void Publisher::
detach(Subscriber *s)
{
// inefficient for large nubmer of susbscribers
subscribers_.remove(s);
}
class Mediator;
class SpreadData;
class DataElement;
class DataVisitor : public Publisher, public Subscriber
{
public:
virtual ~DataVisitor() {}
// visit method
virtual void visit_SpreadData(SpreadData *SD) = 0;
// from Publisher::
void update(const PublishEvent *e) override;
void setMediator(Mediator *m)
{
m_ = m;
}
float get_payload() const
{
return payload_;
}
void set_payload(float p)
{
payload_ = p;
}
virtual void gendata(DataElement*) = 0;
protected:
DataVisitor() {}
private:
Mediator *m_;
float payload_;
};
class DataElement
{
public:
virtual ~DataElement() {};
void Accept(DataVisitor&);
protected:
DataElement() {};
};
void DataElement::Accept(DataVisitor &d)
{
d.gendata(this);
}
class SpreadData : public DataElement
{
public:
typedef std::vector<float> return_data_type;
SpreadData() { initiate(); };
SpreadData(std::string filename) { initiate();};
void printdata() const
{
std::copy(data_.begin(),
data_.end(),
std::ostream_iterator<float>(std::cout, " : "));
std::cout << std::endl;
}
return_data_type getdata() const
{
return data_;
}
private:
void initiate()
{
for(int i=0;i<100;i++)
data_.push_back(static_cast<float>(i));
}
return_data_type data_;
};
void DataVisitor::update(const PublishEvent *e)
{
// implementation details
};
template<int N>
class Visitor_pick : public DataVisitor
{
public:
Visitor_pick()
{set_payload(0.); }
// from DataVisitor
void visit_SpreadData(SpreadData*) override;
// from DataVisitor
void gendata(DataElement*);
};
template<int N>
void Visitor_pick<N>::visit_SpreadData(SpreadData *SD)
{
SD->Accept(*this);
}
template<int N>
void Visitor_pick<N>::gendata(DataElement *d)
{
// implementation details
SpreadData *SD = dynamic_cast<SpreadData*>(d);
SpreadData::return_data_type r = SD->getdata();
set_payload(r[N]);
}
class Mediator
{
public:
virtual ~Mediator() = default;
virtual void mediate(DataElement*) = 0;
protected:
Mediator() = default;
virtual void CreateVisitors() = 0;
std::list<DataVisitor*> visitors_;
};
class Mediator_1 : public Mediator
{
public:
Mediator_1()
{
CreateVisitors();
}
void mediate(DataElement*);
private:
void CreateVisitors();
};
void Mediator_1::CreateVisitors()
{
visitors_.push_back(new Visitor_pick<37>());
visitors_.push_back(new Visitor_pick<42>());
visitors_.push_back(new Visitor_pick<47>());
visitors_.push_back(new Visitor_pick<52>());
visitors_.push_back(new Visitor_pick<57>());
}
void Mediator_1::mediate(DataElement *SD)
{
typedef std::mem_fun1_t<void,DataVisitor,SpreadData*> Visitor_fn;
std::cout << "Mediating hard..." << std::endl;
std::vector<std::thread> threadVec;
for(auto &v : visitors_)
{
// Use Visitor_fn to spawn thread on
// unary function v->visit_SpreadData,
// place at back of threadVec
}
for_each(threadVec.begin(), threadVec.end(),
std::mem_fn(&std::thread::join));
for(auto &v : visitors_)
std::cout << "Payload: " << v->get_payload() << std::endl;
}
int main(int argc, char **argv)
{
SpreadData *SD = new SpreadData();
Mediator_1 *M = new Mediator_1();
M->mediate(SD);
delete SD;
delete M;
return 0;
}

Dynamic Object in C++?

I realize that I'll most likely get a lot of "you shouldn't do that because..." answers and they are most welcome and I'll probably totally agree with your reasoning, but I'm curious as to whether this is possible (as I envision it).
Is it possible to define a type of dynamic/generic object in C++ where I can dynamically create properties that are stored and retrieved in a key/value type of system? Example:
MyType myObject;
std::string myStr("string1");
myObject.somethingIJustMadeUp = myStr;
Note that obviously, somethingIJustMadeUp is not actually a defined member of MyType but it would be defined dynamically. Then later I could do something like:
if(myObject.somethingIJustMadeUp != NULL);
or
if(myObject["somethingIJustMadeUp"]);
Believe me, I realize just how terrible this is, but I'm still curious as to whether it's possible and if it can be done in a way that minimizes it's terrible-ness.
C++Script is what you want!
Example:
#include <cppscript>
var script_main(var args)
{
var x = object();
x["abc"] = 10;
writeln(x["abc"]);
return 0;
}
and it's a valid C++.
You can do something very similar with std::map:
std::map<std::string, std::string> myObject;
myObject["somethingIJustMadeUp"] = myStr;
Now if you want generic value types, then you can use boost::any as:
std::map<std::string, boost::any> myObject;
myObject["somethingIJustMadeUp"] = myStr;
And you can also check if a value exists or not:
if(myObject.find ("somethingIJustMadeUp") != myObject.end())
std::cout << "Exists" << std::endl;
If you use boost::any, then you can know the actual type of value it holds, by calling .type() as:
if (myObject.find("Xyz") != myObject.end())
{
if(myObject["Xyz"].type() == typeid(std::string))
{
std::string value = boost::any_cast<std::string>(myObject["Xyz"]);
std::cout <<"Stored value is string = " << value << std::endl;
}
}
This also shows how you can use boost::any_cast to get the value stored in object of boost::any type.
This can be a solution, using RTTI polymorphism
#include <map>
#include <memory>
#include <iostream>
#include <stdexcept>
namespace dynamic
{
template<class T, class E>
T& enforce(T& z, const E& e)
{ if(!z) throw e; return z; }
template<class T, class E>
const T& enforce(const T& z, const E& e)
{ if(!z) throw e; return z; }
template<class Derived>
class interface;
class aggregate;
//polymorphic uncopyable unmovable
class property
{
public:
property() :pagg() {}
property(const property&) =delete;
property& operator=(const property&) =delete;
virtual ~property() {} //just make it polymorphic
template<class Interface>
operator Interface*() const
{
if(!pagg) return 0;
return *pagg; //let the aggregate do the magic!
}
aggregate* get_aggregate() const { return pagg; }
private:
template<class Derived>
friend class interface;
friend class aggregate;
static unsigned gen_id()
{
static unsigned x=0;
return enforce(++x,std::overflow_error("too many ids"));
}
template<class T>
static unsigned id_of()
{ static unsigned z = gen_id(); return z; }
aggregate* pagg;
};
template<class Derived>
class interface: public property
{
public:
interface() {}
virtual ~interface() {}
unsigned id() const { return property::id_of<Derived>(); }
};
//sealed movable
class aggregate
{
public:
aggregate() {}
aggregate(const aggregate&) = delete;
aggregate& operator=(const aggregate&) = delete;
aggregate(aggregate&& s) :m(std::move(s.m)) {}
aggregate& operator=(aggregate&& s)
{ if(this!=&s) { m.clear(); std::swap(m, s.m); } return *this; }
template<class Interface>
aggregate& add_interface(interface<Interface>* pi)
{
m[pi->id()] = std::unique_ptr<property>(pi);
static_cast<property*>(pi)->pagg = this;
return *this;
}
template<class Inteface>
aggregate& remove_interface()
{ m.erase[property::id_of<Inteface>()]; return *this; }
void clear() { m.clear(); }
bool empty() const { return m.empty(); }
explicit operator bool() const { return empty(); }
template<class Interface>
operator Interface*() const
{
auto i = m.find(property::id_of<Interface>());
if(i==m.end()) return nullptr;
return dynamic_cast<Interface*>(i->second.get());
}
template<class Interface>
friend aggregate& operator<<(aggregate& s, interface<Interface>* pi)
{ return s.add_interface(pi); }
private:
typedef std::map<unsigned, std::unique_ptr<property> > map_t;
map_t m;
};
}
/// this is a sample on how it can workout
class interface_A: public dynamic::interface<interface_A>
{
public:
virtual void methodA1() =0;
virtual void methodA2() =0;
};
class impl_A1: public interface_A
{
public:
impl_A1() { std::cout<<"creating impl_A1["<<this<<"]"<<std::endl; }
virtual ~impl_A1() { std::cout<<"deleting impl_A1["<<this<<"]"<<std::endl; }
virtual void methodA1() { std::cout<<"interface_A["<<this<<"]::methodA1 on impl_A1 in aggregate "<<get_aggregate()<<std::endl; }
virtual void methodA2() { std::cout<<"interface_A["<<this<<"]::methodA2 on impl_A1 in aggregate "<<get_aggregate()<<std::endl; }
};
class impl_A2: public interface_A
{
public:
impl_A2() { std::cout<<"creating impl_A2["<<this<<"]"<<std::endl; }
virtual ~impl_A2() { std::cout<<"deleting impl_A2["<<this<<"]"<<std::endl; }
virtual void methodA1() { std::cout<<"interface_A["<<this<<"]::methodA1 on impl_A2 in aggregate "<<get_aggregate()<<std::endl; }
virtual void methodA2() { std::cout<<"interface_A["<<this<<"]::methodA2 on impl_A2 in aggregate "<<get_aggregate()<<std::endl; }
};
class interface_B: public dynamic::interface<interface_B>
{
public:
virtual void methodB1() =0;
virtual void methodB2() =0;
};
class impl_B1: public interface_B
{
public:
impl_B1() { std::cout<<"creating impl_B1["<<this<<"]"<<std::endl; }
virtual ~impl_B1() { std::cout<<"deleting impl_B1["<<this<<"]"<<std::endl; }
virtual void methodB1() { std::cout<<"interface_B["<<this<<"]::methodB1 on impl_B1 in aggregate "<<get_aggregate()<<std::endl; }
virtual void methodB2() { std::cout<<"interface_B["<<this<<"]::methodB2 on impl_B1 in aggregate "<<get_aggregate()<<std::endl; }
};
class impl_B2: public interface_B
{
public:
impl_B2() { std::cout<<"creating impl_B2["<<this<<"]"<<std::endl; }
virtual ~impl_B2() { std::cout<<"deleting impl_B2["<<this<<"]"<<std::endl; }
virtual void methodB1() { std::cout<<"interface_B["<<this<<"]::methodB1 on impl_B2 in aggregate "<<get_aggregate()<<std::endl; }
virtual void methodB2() { std::cout<<"interface_B["<<this<<"]::methodB2 on impl_B2 in aggregate "<<get_aggregate()<<std::endl; }
};
int main()
{
dynamic::aggregate agg1;
agg1 << new impl_A1 << new impl_B1;
dynamic::aggregate agg2;
agg2 << new impl_A2 << new impl_B2;
interface_A* pa = 0;
interface_B* pb = 0;
pa = agg1; if(pa) { pa->methodA1(); pa->methodA2(); }
pb = *pa; if(pb) { pb->methodB1(); pb->methodB2(); }
pa = agg2; if(pa) { pa->methodA1(); pa->methodA2(); }
pb = *pa; if(pb) { pb->methodB1(); pb->methodB2(); }
agg2 = std::move(agg1);
pa = agg2; if(pa) { pa->methodA1(); pa->methodA2(); }
pb = *pa; if(pb) { pb->methodB1(); pb->methodB2(); }
return 0;
}
tested with MINGW4.6 on WinXPsp3
Yes it is terrible. :D
It had been done numerous times to different extents and success levels.
QT has Qobject from which everything related to them decends.
MFC has CObject from which eveything decends as does C++.net
I don't know if there is a way to make it less bad, I guess if you avoid multiple inheritance like the plague (which is otherwise a useful language feature) and reimplement the stdlib it would be better. But really if that is what you are after you are probably using the wrong language for the task.
Java and C# are much better suited to this style of programming.
#note if I have read your question wrong just delete this answer.
Check out Dynamic C++