Problem with Command Pattern under Visual Studio 2008 (C++) - c++

I've a problem with this pattern under c++ on VS 2008.
The same code has been tested in gcc (linux, mac and mingw for
widnows) and it works.
I copy/paste the code here:
class MyCommand {
public:
virtual void execute() = 0;
virtual ~MyCommand () {};
};
class MyOperation {
public:
virtual void DoIt() {}; //I also write it not inline
};
class MyOperationDerived : public MyOperation {
public:
virtual void DoIt() {}; //I also write it not inline
};
class MyUndoStackCommand : public MyCommand {
public:
typedef void(MyOperation::*Action)();
MyUndoStackCommand(MyOperation *rec, Action action);
/*virtual*/ void execute();
/*virtual*/ ~MyUndoStackCommand();
private:
MyOperation *myReceiver;
Action myAction ;
};
in cpp:
#include "MyUndoStackCommand.h"
#include "MyOperation.h"
MyUndoStackCommand::~MyUndoStackCommand() {
}
MyUndoStackCommand::MyUndoStackCommand(myOperation *rec, Action
action): myReceiver(rec), myAction(action) {
}
void MyUndoStackCommand::execute() {
((myReceiver)->*(myAction))();
}
use in main.cpp:
MyReceiver receiver;
MyUndoStackCommand usc(&receiver, &MyOperation::DoIt);
usc.execute();
when I debug under visual studio only if I set inside MyUndoStackCommand, directly
myAction = &MyOperation::DoIt , it works, otherwise not.
Any advice?
thank you very much,
dan
Edit: The following code compiles with g++ - changes by Neil Butterworth flagged as //NB.
class MyCommand {
public:
virtual void execute() = 0;
virtual ~MyCommand () {};
};
class MyOperation {
public:
virtual void DoIt() {}; //I also write it not inline
};
class MyOperationDerived : public MyOperation {
public:
virtual void DoIt() {}; //I also write it not inline
};
class MyUndoStackCommand : public MyCommand {
public:
typedef void(MyOperation::*Action)();
MyUndoStackCommand(MyOperation *rec, Action action);
/*virtual*/ void execute();
/*virtual*/ ~MyUndoStackCommand();
private:
MyOperation *myReceiver;
Action myAction ;
};
MyUndoStackCommand::~MyUndoStackCommand() {
}
MyUndoStackCommand::MyUndoStackCommand(MyOperation *rec, //NB
Action action)
: myReceiver(rec), myAction(action) {
}
void MyUndoStackCommand::execute() {
((myReceiver)->*(myAction))();
}
int main() {
MyOperation receiver; //NB
MyUndoStackCommand usc(&receiver, &MyOperation::DoIt);
usc.execute();
}

With Neils edit this works fine in Visual Studio 2008.
// command.h
#pragma once
#include <iostream> // added for printing
using namespace std; // added for printing
class MyCommand {
public:
virtual void execute() = 0;
virtual ~MyCommand () {};
};
class MyOperation {
public:
virtual void DoIt() {
cout << "myoperation::doit()" << endl;
}; //I also write it not inline
};
class MyOperationDerived : public MyOperation {
public:
virtual void DoIt() {
cout << "myoperationderived::doit()" << endl;
}; //I also write it not inline
};
class MyUndoStackCommand : public MyCommand {
public:
typedef void(MyOperation::*Action)();
MyUndoStackCommand(MyOperation *rec, Action action);
/*virtual*/ void execute();
/*virtual*/ ~MyUndoStackCommand();
private:
MyOperation *myReceiver;
Action myAction;
};
// command.cpp
#include "command.h"
MyUndoStackCommand::~MyUndoStackCommand() {
}
MyUndoStackCommand::MyUndoStackCommand(/*m*/ MyOperation *rec, Action
action): myReceiver(rec), myAction(action) {
}
void MyUndoStackCommand::execute() {
((myReceiver)->*(myAction))();
}
// main.cpp
#include "command.h"
int main(){
MyOperationDerived receiver;
MyUndoStackCommand usc(&receiver, &MyOperation::DoIt);
usc.execute();
}
Will print:
"myoperationderived::doit()"

Related

C++ `enable_shared_from_this` and `shared_From_this()` not compiling or running

I am having a hard time trying to compile the following code using clang compiler. I am not sure if I am using enable_shared_from_this and shared_From_this() in the right way, or breaking rule inadvertently. Can someone point me out what is exactly causing problem.
#include <iostream>
#include <memory>
class IB {
public:
virtual void Calle() =0;
virtual void Show() = 0;
};
class IC {
public:
virtual void Calle() =0;
virtual void Print() =0;
};
class CB;
class CC;
class CA : public std::enable_shared_from_this<CA> {
private:
std::shared_ptr<IB> m_ib;
public:
CA()
: m_ib(std::make_shared<CB>(shared_from_this())) {
std::cout << "Created CA obj\n";
}
void Calle() {
if(m_ib) m_ib->Calle();
// Show();
}
void Show() {
std::cout << "Printing from here. CA\n";
}
};
class CB : public IB, public std::enable_shared_from_this<CA> {
private:
std::shared_ptr<IC> m_ic;
std::shared_ptr<CA> m_ca;
public:
CB() : CB(nullptr){}
CB(const std::shared_ptr<CA> a)
: m_ca(a)
, m_ic(std::make_shared<CC>(shared_from_this())) {
std::cout << "Created CB obj\n";
}
virtual void Calle() override;
virtual void Show() override;
};
void CB::Calle() {
if(m_ca) m_ca->Show();
if(m_ic) m_ic->Print();
Show();
}
void CB::Show() {
std::cout << "Printing from here. CB\n";
}
class CC : public IC, public std::enable_shared_from_this<CA> {
private:
std::shared_ptr<IB> m_ib;
public:
CC()
: CC(nullptr){}
CC(const std::shared_ptr<CB> b)
: m_ib(b){
std::cout << "Created CC obj\n";
}
virtual void Calle() override;
virtual void Print() override;
};
void CC::Calle() {
if(m_ib) m_ib->Show();
}
void CC::Print() {
std::cout << "Printing from here. CC\n";
}
int main() {
auto a = std::make_shared<CA>();
a->Calle();
return 0;
}

Error"pure virtual method called",when this method has been override

I'm trying to practice "Observer Design Pattern". When I thought a abstract's pure virtual method has been override by it's derived class, a error occurred.
There is a observer which is an abstract class in a independent file:
#ifndef DESIGN_PATTERNS_OBSERVER_H
#define DESIGN_PATTERNS_OBSERVER_H
#include "subject.h"
class Subject;
class Observer{
protected:
Observer();
public:
virtual ~Observer();
virtual void update(Subject *the_changed_subject) = 0;
};
Observer::Observer() {}
Observer::~Observer() {}
#endif //DESIGN_PATTERNS_OBSERVER_H
Observer defined a pure virtual method "update" which overrides as follow:
#ifndef DESIGN_PATTERNS_CONCRETE_OBSERVER_H
#define DESIGN_PATTERNS_CONCRETE_OBSERVER_H
#include <iostream>
#include "observer.h"
#include "concrete_subject.h"
class ConcreteObserver : public Observer{
public:
void update(Subject *the_changed_subject) override {
auto cs = dynamic_cast<ConcreteSubject *>(the_changed_subject);
std::cout << "status changed to " << cs->get_status() << std::endl;
}
};
#endif //DESIGN_PATTERNS_CONCRETE_OBSERVER_H
And also there is a subject which is an abstract class too.The error "pure virtual method called" happened in "notify" method where I had marked.
From debug, it seems "notify" uses Observer's "update" rather than ConcreteObserver's.
However,in main function the _observers should stored pointers of ConcreteObservers which override "update".
#ifndef DESIGN_PATTERNS_SUBJECT_H
#define DESIGN_PATTERNS_SUBJECT_H
#include <list>
#include "observer.h"
class Subject {
private:
std::list<Observer*> *_observers;
protected:
Subject();
public:
virtual ~Subject();
virtual void attach(Observer*);
virtual void detach(Observer*);
virtual void notify();
};
Subject::Subject() {
_observers = new std::list<Observer*>;
}
Subject::~Subject() {
delete _observers;
}
void Subject::attach(Observer *o) {
_observers->push_back(o);
}
void Subject::detach(Observer *o) {
_observers->remove(o);
}
void Subject::notify() {
for (Observer* observer : *_observers) {
//here is where error comes out, found by debug
observer->update(this);
}
}
#endif //DESIGN_PATTERNS_SUBJECT_H
And it has a derived class "ConcreteSubject":
#ifndef DESIGN_PATTERNS_CONCRETE_SUBJECT_H
#define DESIGN_PATTERNS_CONCRETE_SUBJECT_H
#include "subject.h"
class ConcreteSubject : public Subject {
private:
int status;
public:
ConcreteSubject() {
status = 0;
}
void set_status(int s) {
this->status = s;
Subject::notify();
}
int get_status() {
return status;
}
};
#endif //DESIGN_PATTERNS_CONCRETE_SUBJECT_H
The main function:
#include <iostream>
#include <vector>
#include "singleton.h"
#include "observer/concrete_subject.h"
#include "observer/concrete_observer.h"
void test2() {
ConcreteSubject concreteSubject;
std::vector<ConcreteObserver> observers;
for (int i = 0; i < 5; ++i) {
ConcreteObserver observer = ConcreteObserver();
concreteSubject.attach(&observer);
observers.push_back(observer);
}
concreteSubject.set_status(2);
}
int main() {
test2();
return 0;
}
As I mentioned before, the _observers of ConcreteSubject's super class Subject should stored pointers of ConcreteObservers which override "update" already.
I don't understand why Observer's "update" still called.
Here is another strange thing.I make a small test has almost the same relationship of classes I showed.But no error occured.
class ABaseA{
public:
virtual void do_some() = 0;
};
class MidA : public ABaseA{
public:
void do_some() override {
cout << "real do some" << endl;
}
};
class ABaseB{
private:
list<ABaseA*> *bases;
public:
ABaseB() {
bases = new list<ABaseA*>();
}
virtual ~ABaseB() = default;
virtual void add(ABaseA* item) {
bases->push_back(item);
}
virtual void do_active() {
for(ABaseA *p : *bases) {
p->do_some();
}
}
};
class MidB : public ABaseB{
public:
MidB() = default;
void active() {
ABaseB::do_active();
}
};
void test3() {
MidA midA;
MidB midB;
midB.add(&midA);
midB.active();
}
The only difference is this code is in one file.
In the file of Subject.h you should be transfer below code to Subject.cpp:
Subject::Subject() {
_observers = new std::list<Observer*>;
}
Subject::~Subject() {
delete _observers;
}
void Subject::attach(Observer *o) {
_observers->push_back(o);
}
void Subject::detach(Observer *o) {
_observers->remove(o);
}
void Subject::notify() {
for (Observer* observer : *_observers) {
//here is where error comes out, found by debug
observer->update(this);
}
}
Also you should be add class Observer; in top of Subject.h
#include <list>
#include "Observer.h"
class Observer; //you should be add this line
class Subject {
private:
std::list<Observer*> *_observers;
protected:
Subject();
public:
virtual ~Subject();
virtual void attach(Observer*);
virtual void detach(Observer*);
virtual void notify();
};

C++ 11 avoiding "Call Super" code smell

I'm looking for ways to avoid the "call super" code smell. This code smell is present when a subclass is required to invoke the super class's version of a virtual function when re-implementing that function.
class Base
{
public:
virtual void foo(){ ... }
}
class Derived : public Base
{
public:
virtual void foo(){ Base::foo();// required! ... }
}
If inheritance went only a single layer deep, I could use the template method
class Base
{
public:
void foo(){ ... ; foo_impl(); }
protected:
virtual void foo_impl(){}
}
class Derived : public Base
{
protected:
virtual void foo_impl(){ ... }
}
But if I need to subclass Derived, I'm back where I started.
I'm considering a registration approach.
class Base
{
public:
Base()
{
_registerCallback( [this](){ _baseFoo(); } );
}
void foo()
{
for( auto f : _callbacks )
f();
}
protected:
void registerCallback( std::function<void()> f )
{
_callbacks << f;
}
private:
void _baseFoo() { ... }
std::list< std::function<void()> > _callbacks;
}
class Derived : public Base
{
public:
Derived()
{
_registerCallback( [this](){ _derivedFoo(); } );
}
private:
virtual void _derivedFoo(){ ... }
}
Is there a more standard approach? Any problems with or improvements to this approach?
Use of
class Derived : public Base
{
public:
virtual void foo(){ Base::foo();// required! ... }
}
is the best approach IMO. I am not sure why you would consider that "code smell".
The potential for error is higher in the last approach you suggested.
It's easier to detect a missed call to Base::foo().
If all the classed derived from Base need to implement what Base::foo() does, it's better that the common code be in Base::foo(). The derived classes simply need to make the call.
For what it's worth, we use the pattern at my work a lot and it has proven to be robust over 20+ years of usage.
You can continue using template methods all the way down if you introduce new virtual member function on each level and override it on next one:
template <typename> struct tag {};
class Base
{
public:
void foo() { ... ; foo_impl(tag<Base>{}); }
protected:
virtual void foo_impl(tag<Base>) {}
};
class Derived1 : public Base
{
protected:
virtual void foo_impl(tag<Base>) override final { ... ; foo_impl(tag<Derived1>{}); }
virtual void foo_impl(tag<Derived1>) {}
};
class Derived2 : public Derived1
{
protected:
virtual void foo_impl(tag<Derived1>) override final { ... ; foo_impl(tag<Derived2>{}); }
virtual void foo_impl(tag<Derived2>) {}
};
class Derived3 : public Derived2
{
protected:
virtual void foo_impl(tag<Derived2>) override final { ... ; foo_impl(tag<Derived3>{}); }
virtual void foo_impl(tag<Derived3>) {}
};
If you dislike tag dispatch you can just give methods different names instead, perhaps something like foo_impl_N.
I consider all this overengineering.
chris mentioned a primary concern regards childs not calling their parent's corresponding member functions, this gives an idea about fixing that part:
#include <cassert>
class Base {
public:
void foo() {
foo_impl();
assert(base_foo_called && "call base class foo_impl");
}
protected:
virtual void foo_impl() { base_foo_called = true; }
private:
bool base_foo_called = false;
};
class DerivedFine : public Base {
protected:
void foo_impl() override {
Base::foo_impl();
}
};
class DerivedDerivedFine : public DerivedFine {
protected:
void foo_impl() override {
DerivedFine::foo_impl();
}
};
class DerivedDerivedNotFine : public DerivedFine {
protected:
void foo_impl() override {}
};
int main() {
DerivedFine foo;
foo.foo();
DerivedDerivedFine bar;
bar.foo();
DerivedDerivedNotFine baz;
baz.foo(); // this asserts
}
CRTP can solve everything.
For each foo method, you implement an empty non-virtual foo_before() that does nothing in your CRTP helper.
CRTP helper takes a derived and a base. Its virtual void foo() invokes static_cast<Derived*>(this)->foo_before() then Base::foo() then after_foo().
struct Base {
virtual void foo() { std::cout << "foo\n"; }
virtual ~Base() {};
};
template<class D, class B=Base>
struct foo_helper:B {
virtual void foo() {
static_cast<D*>(this)->before_foo();
this->B::foo();
static_cast<D*>(this)->after_foo();
}
private:
void before_foo() {}; void after_foo() {};
};
struct Derived1 : foo_helper<Derived1> {
void before_foo() { std::cout << "before1\n"; }
};
struct Derived2 : foo_helper<Derived2> {
void before_foo() { std::cout << "before2\n"; }
void after_foo() { std::cout << "after2\n"; }
};
struct DoubleDerived : foo_helper<DoubleDerived, Derived2> {
void after_foo() { std::cout << "even more after\n"; }
};
int main() {
std::cout << "---- Derived1\n";
Derived1 d1;
d1.foo();
std::cout << "---- Derived2\n";
Derived2 d2;
d2.foo();
std::cout << "---- DoubleDerived\n";
DoubleDerived dd;
dd.foo();
}
Live example.
Output:
---- Derived1
before1
foo
---- Derived2
before2
foo
after2
---- DoubleDerived
before2
foo
after2
even more after
Here's an idea inspired by this answer
The idea is to use the fact that constructors and destructors of a struct / class provides a sort of "pre/post function calling" mechanism that gets inherited. So instead of doing the pre/post function calls in the virtual method itself, we can use a functor and define the pre/post function call in the constructor / destructor. That way, functors that inherit from the base functor will inherit the pre/post function call.
Code
struct BasePrePostFunctor
{
BasePrePostFunctor()
{
printf("Base pre-func\n");
}
virtual void operator()()
{
printf("Base Main func\n");
}
~BasePrePostFunctor()
{
printf("Base post-func\n");
}
};
struct DerivedPrePostFunctor : BasePrePostFunctor
{
DerivedPrePostFunctor()
{
printf("Derived pre-func\n");
}
void operator()() override
{
printf("Derived main func\n");
}
~DerivedPrePostFunctor()
{
printf("Derived post-func\n");
}
};
class BaseClass
{
public:
virtual void virtual_func()
{
BasePrePostFunctor func;
func();
}
};
class DerivedClass : public BaseClass
{
public:
void virtual_func() override
{
DerivedPrePostFunctor func;
func();
}
};
int main(int argc, char** argv)
{
DerivedClass derived;
derived.virtual_func();
};
Output
Base pre-func
Derived pre-func
Derived main func
Derived post-func
Base post-func

Inheritance and virtual function can't compile (from Head First DP)

I am new to Design Pattern, and I'm trying the first example of (Head First Design Patterns) but I'm trying to code it in C++. I can't compile my code! I don't know why. Here's my code.
#include <iostream>
using namespace std;
class QuackBehavior
{
public:
virtual void quack();
virtual ~QuackBehavior();
};
class Quack : public QuackBehavior
{
public:
void quack()
{
cout<<"Quacking"<<endl;
}
};
class MuteQuack : public QuackBehavior
{
public:
void quack()
{
cout<<"<<< Silence >>>"<<endl;
}
};
class Squeak : public QuackBehavior
{
public:
void quack()
{
cout<<"Squeak"<<endl;
}
};
class FlyBehavior
{
public:
virtual void fly();
virtual ~FlyBehavior();
};
class FlyWithWings : public FlyBehavior
{
public:
void fly()
{
cout<<"I'm flying"<<endl;
}
};
class FlyNoWay : public FlyBehavior
{
public:
void fly()
{
cout<<"I can't fly"<<endl;
}
};
class Duck
{
public:
FlyBehavior *flyBehavior;
QuackBehavior *quackBehavior;
void display();
void performFly()
{
flyBehavior->fly();
}
void performQuack()
{
quackBehavior->quack();
}
};
class MallardDuck : public Duck
{
public:
MallardDuck()
{
quackBehavior = new Quack();
flyBehavior = new FlyWithWings();
}
};
int main()
{
Duck *mallard = new MallardDuck;
cout<<"Test"<<endl;
mallard->performFly();
// mallard->performQuack();
return 0;
}
Thanks for your help.
You get a compile error because you have not provided default definitions for functions in class QuackBehavior and class FlyBehavior.
Either you could provide default implementation or make the functions pure virtual.
Make the below two changes and your code should compile fine.
class QuackBehavior
{
public:
virtual void quack(){}
virtual ~QuackBehavior(){}
};
class FlyBehavior
{
public:
virtual void fly(){}
virtual ~FlyBehavior(){}
};
OR
class FlyBehavior
{
public:
virtual void fly() = 0;
};
class QuackBehavior
{
public:
virtual void quack() = 0;
};

Implementing 2 abstract classes with a common function?

What happens when a class inherits from multiple abstract classes when 2 or more of them have a function with the same name, return type, and arguments?
Assuming all functions here are virtual
Thanks
class C inherits from A and B at the same time and both A & B have virtual void func(int h);
If this is what you mean,
#include <iostream.h>
class A
{
public:
virtual void a_show()=0;
virtual void show()
{
cout<<"A";
}
};
class B
{
public:
virtual void b_show()=0;
virtual void show()
{
cout<<"B";
}
};
class C : public A, public B
{
virtual void a_show()
{}
virtual void b_show()
{}
};
void main()
{
C s;
s.show();
}
The code gives an error with VC++ like
error C2385: 'C::show' is ambiguous
You need to declare show like this :
#include <iostream.h>
class A
{
public:
virtual void a_show()=0;
virtual void show()
{
cout<<"A";
}
};
class B
{
public:
virtual void b_show()=0;
virtual void show()
{
cout<<"B";
}
};
class C : public A, public B
{
public:
virtual void a_show()
{}
virtual void b_show()
{}
void show()
{
cout<<"C";
}
};
void main()
{
C s;
s.show();
}
This sure will give C
C++ also allows to pick an inherited virtual member function (IVMF) as well, so you don't need to override an IVMF. Borrowing the example from mihsathe, we can do the following:
class C : public A, public B {
public:
virtual void a_show() { }
virtual void b_show() { }
using B::show;
// using A:show; // If you want to use show() from A
};