What are they, what's the different between them?
Many sources, like Wikipedia, claim they're the same thing, but others explicitly say the opposite, like sbi in this question:
First: "Visitor Pattern is a way to simulate Double Dispatching in C++." This is, erm, not fully right. Actually, double dispatch is one form of multiple dispatch, which is a way to simulate (the missing) multi-methods in C++.
They are the same.
When you call a virtual method in C++, the actual method to run is based on the runtime type of the object them method is invoked on. This is called "single dispatch" because it depends on the type of a single argument (in this case, the implicit 'this' argument). So, for example, the following:
class Base {
public:
virtual int Foo() { return 3; }
}
class Derived : public Base {
public:
virtual int Foo() { return 123; }
}
int main(int argc, char *argv[]) {
Base* base = new Derived;
cout << "The result is " << base->Foo();
delete base;
return 0;
}
When run, the above program prints 123, not 3. So far so good.
Multiple-dispatch is the ability of a language or runtime to dispatch on both the type of the 'this' pointer and the type of the arguments to the method. Consider (sticking with C++ syntax for the moment):
class Derived;
class Base {
public:
virtual int Foo(Base *b) { cout << "Called Base::Foo with a Base*"; }
virtual int Foo(Derived *d) { cout << "Called Base::Foo with a Derived*"; }
}
class Derived : public Base {
public:
virtual int Foo(Base *b) { cout << "Called Derived::Foo with a Base*"; }
virtual int Foo(Derived *d) { cout << "Called Derived::Foo with a Derived*"; }
}
int main(int argc, char *argv[]) {
Base* base = new Derived;
Base* arg = new Derived;
base->Foo(arg);
delete base;
delete arg;
return 0;
}
If C++ had multiple-dispatch, the program would print out "Called Derived::Foo with a Dervied*". (Sadly, C++ does not have multiple-dispatch, and so the program prints out "Called Derived::Foo with a Base*".)
Double-dispatch is a special case of multiple-dispatch, often easier to emulate, but not terribly common as a language feature. Most languages do either single-dispatch or multiple-dispatch.
Related
First of all, I'm new to Google test, so please forgive my ignorance, if any.
I'm writing unit tests using google test framework for the below class..
class MsgHandler
{
public:
MsgHandler(){}
~MsgHandler(){}
bool decode_data(unsigned char*, unsigned int,char *);
bool handle_req_state_data(char *, char *);
};
bool MsgHandler::handle_req_state_data(char *a, char *b)
{
printf("handle_req_state_data called\n");
return true;
}
bool MsgHandler::decode_data(unsigned char *a, unsigned int b,char *c)
{
printf("decode_data called\n");
handle_req_state_data(c, c);
return true;
}
As a first step, I have created the mock class as below
class MsgHandlerMock : public MsgHandler
{
public:
MsgHandlerMock()
{
}
virtual ~MsgHandlerMock() {}
MOCK_METHOD(bool, handle_req_state_data, (char *, char *), (const));
//MOCK_METHOD(int, decode_data, (unsigned char*, unsigned int ,char* ));
private:
};
Below is the test function
TEST_F(TestClass, test01)
{
MsgHandlerMock mockObj;
//EXPECT_CALL(mockObj, decode_data(::testing::_,::testing::_,::testing::_)).Times(1);
EXPECT_CALL(mockObj, handle_req_state_data(::testing::_,::testing::_)).Times(1);
mockObj.decode_data(0,0,0);
}
My intention of this test is to make sure 'handle_req_state_data' is called when I call 'decode_data' with a certain message. But my test fails with below error
decode_data called
handle_req_state_data called
...
Actual function call count doesn't match EXPECT_CALL(mockObj, handle_req_state_data(::testing::_,::testing::_))...
Expected: to be called once
Actual: never called - unsatisfied and active
[ FAILED ] TestClass.test01 (1 ms)
[----------] 1 test from TestClass (1 ms total)
Can someone help me on how to validate the inner method calls with EXPECT_CALL validators?
The function is not virtual, so can't be overridden by the mock, decode_data does not use dynamic dispatch and call the original method MsgHandler::handle_req_state_data.
virtual bool handle_req_state_data(char *, char *);
MOCK_METHOD(bool, handle_req_state_data, (char *, char *), (override));
Inspired by that Google doc "ForDummies" :), I am trying a simple Google Mock with Google Test example as follows:
#include <gtest/gtest.h>
#include <gmock/gmock.h>
using ::testing::_;
class A
{
public:
A()
{
std::cout << "A()" << std::endl;
}
virtual ~A()
{
std::cout << "~A()" << std::endl;
}
virtual int incVirtual(int i)
{
return i + 1;
}
};
class MockA: public A
{
public:
MOCK_METHOD1(incVirtual, int(int));
};
TEST(Test, IncTest) {
MockA a;
EXPECT_CALL(a, incVirtual(_));
printf("n == %d\n", a.incVirtual(0));
}
int main(int argc, char **argv)
{
::testing::InitGoogleMock(&argc, argv);
return RUN_ALL_TESTS();
}
When I run it, I get n == 0:
[==========] Running 1 test from 1 test case.
[----------] Global test environment set-up.
[----------] 1 test from Test
[ RUN ] Test.IncTest
A()
n == 0
~A()
whereas I expect it to be n == 1. So I wonder if just defining MOCK_METHODx in the mock class is not enough for mocking the base class method and something additional needs to be done to make MockA::incVirtual call A::incVirtual?
This is behaving the way it should. By mocking your function, the MockA class has essentially overridden the A class implementation with a "do nothing" implementation.
If you want to call A::incVirtual() when calling MockA::incVirtual(), try the following
EXPECT_CALL(a, incVirtual(_)).WillOnce(Invoke(&a, &A::incVirtual));
For boost::serialize I am trying to define a custom class with its own serialize function, similar to http://www.boost.org/doc/libs/1_53_0/libs/serialization/doc/tutorial.html#simplecase However, the program just segfaults. Why?
class Test {
public:
unsigned short testid;
template<class Archive>
void serialize(Archive & ar, const unsigned int version)
{
ar & testid;
}
};
int main() {
Test mytest = {100};
std::ofstream ofsx("test.tmp");
boost::archive::binary_oarchive oax(ofsx);
oax << mytest;
cout << "Exported";
exit(1);
}
I also tried the non-intrusive version with the same result.
Am I missing something?
The problem was caused by linking against outdated libraries.
I created a dll with VS C++ (of course as a dll project) with the following code of the header file:
#pragma once
#include <iostream>
#include "..\..\profiles/ProfileInterface.h"
using namespace std;
extern "C" __declspec(dllexport) class CExportCoordinator: public CProfileInterface
{
public:
CExportCoordinator(void);
virtual ~CExportCoordinator(void);
CProfileInterface* Create();
void Initialize();
void Start();
};
Here is .cpp file of the dll:
#include "StdAfx.h"
#include "ExportCoordinator.h"
CExportCoordinator::CExportCoordinator(void)
{
}
CExportCoordinator::~CExportCoordinator(void)
{
}
CProfileInterface* CExportCoordinator::Create(){
cout << "ExportCoordinator3 created..." << endl;
return new CExportCoordinator();
}
void CExportCoordinator::Initialize(){
cout << "ExportCoordinator3 initialized..." << endl;
}
void CExportCoordinator::Start(){
cout << "ExportCoordinator3 started..." << endl;
}
I exported the whole class CExportCoordinator because I need to use all three methods it offers. Following is the code from the main application loading the, above given, dll on the fly.
typedef CProfileInterface* (WINAPI*Create)();
int _tmain(int argc, _TCHAR* argv[])
{
HMODULE hLib = LoadLibrary(name);
if(hLib==NULL) {
cout << "Unable to load library!" << endl;
return NULL;
}
char mod[MAXMODULE];
GetModuleFileName(hLib, (LPTSTR)mod, MAXMODULE);
cout << "Library loaded: " << mod << endl;
Create procAdd = (Create) GetProcAddress(hLib,"Create");
if (!procAdd){
cout << "function pointer not loaded";
}
return;
}
On the output I get that correct library is loaded, but that function pointer procAdd is NULL. I thought it had something to do with name mangling and added extern "C" when exporting the class in header of dll, but nothing changed. Btw, I used dll export viewer for viewing the exported functions of the class, and the whole class is exported correctly.
Any help?
UPDATE
there is an error in the header file of dll. I shouldn't be using extern "C" __declspec(dllexport) before class because then class won't be exported at all. If I use class __declspec(dllexport) CExportCoordinator then the class is exported correctly, but anyway I can't get the address of the function other than NULL.
extern "C" __declspec(dllexport) class CExportCoordinator: public CProfileInterface
{
This is nonsense. A class cannot be "extern C"
... inside the class ...
CProfileInterface* Create();
This creates a member function of the class, which is not probably what you want. For one thing, it will be mangled in the DLL, second, it will not be callable without the this pointer. Probably, you need this declaration:
extern "C" __declspec(dllexport) CProfileInterface* Create();
and implemntation:
extern "C" __declspec(dllexport) CProfileInterface* Create(){
cout << "ExportCoordinator3 created..." << endl;
return new CExportCoordinator();
}
It seems to me that you should declare Create method as a static method and export this method only. If you will stay have NULL in GetProcAddress you should examine exports of your DLL with respect of Dependency Walker (see http://www.dependencywalker.com/) and modify the name of the function "Create" to something like "_Create" or "_Create#2".
I have an inheritance hierarchy similar to below and I want to write my DAL to persist these objects but am unsure as to the best way of structuring it?
Pet <- Dog <- Alsation and Labrador
Pet <- Cat <- Persian and Tabby
Although all classes inherit from Pet, each method will need to call a different stored procedure and add different sql parameters. There will be some common parameters though.
A few ideas:
(1) PetDal with overloaded save method that takes in each derived type.
(2) PetDal with separate SaveLabrador, SaveTabby methods.
(3) Base PetDal plus inherited LabradorDal, TabbyDal classes, one per dervied type with a common interface. eg void Save(Pet pet) which would need to cast the pet to the derived type within each method (strategy method).
(4) Some other way.
(1) and (2) are really the same, just syntactically different. One problem with (4) is that if you want to deal with different persistent types (flat files, databases etc) then you will have to have a class for each permutation (AlsationToFileDAL, AlsationToSybaseDAL, etc).
You could use (1)/(2) with double dispatch, e.g.:
// pets.h
#include <string>
#include <iostream>
class Alsation;
class Persian;
class PetDAL
{
public:
virtual ~PetDAL () {}
virtual void save (const Alsation* alsation) = 0;
virtual void save (const Persian* persian) = 0;
};
class Pet
{
std::string name_;
public:
Pet (const std::string& name) : name_ (name)
{}
virtual ~Pet () {}
std::string getName () const
{
return name_;
}
virtual void save (PetDAL* dal) const = 0;
};
class Dog : public Pet
{
bool sleepWalks_;
public:
Dog (const std::string& name, bool sleepWalks) : Pet (name), sleepWalks_ (sleepWalks)
{}
bool getSleepWalks () const {return sleepWalks_;}
};
class Alsation : public Dog
{
public:
Alsation (const std::string& name, bool sleepWalks) : Dog (name, sleepWalks)
{}
virtual void save (PetDAL* dal) const
{
dal->save (this);
}
};
class Cat : public Pet
{
int purrsPerMinute_;
public:
Cat (const std::string& name, int purrsPerMinute) : Pet (name), purrsPerMinute_ (purrsPerMinute)
{}
int getPurrsPerMinute () const {return purrsPerMinute_;}
};
class Persian : public Cat
{
public:
Persian (const std::string& name, int purrsPerMinute) : Cat (name, purrsPerMinute)
{}
virtual void save (PetDAL* dal) const
{
dal->save (this);
}
};
class PetDALCoutImpl : public PetDAL
{
public:
virtual void save (const Alsation* alsation)
{
std::cout << "Saving alsation " << std::endl
<< "\tname=" << alsation->getName () << std::endl
<< "\tsleepwalks=" << alsation->getSleepWalks () << std::endl;
}
virtual void save (const Persian* persian)
{
std::cout << "Saving persian " << std::endl
<< "\tname=" << persian->getName () << std::endl
<< "\tpurrsPerMinute=" << persian->getPurrsPerMinute () << std::endl;
}
};
int test (int argc, char* argv[])
{
Dog* dog = new Alsation ("fido", true);
Cat* cat = new Persian ("dave", 10);
PetDAL* petDAL = new PetDALCoutImpl ();
dog->save (petDAL);
cat->save (petDAL);
delete cat;
delete dog;
return 0;
};
I.e. the Pet base class knows its subclasses can be saved to a DAL, but it has no dependency on the DAL implementations.
Have you thought about using a pattern like the strategy pattern? It might fit your needs as you can have different strategies for different implementations, whilst still using properties/methods from the abstract class?