I have a project with a situation where a function of a wrong object is being called.
To simplify it, I created a new CPP project in visual studio. The project has three files (attached at the bottom) with 2 modules, derived_1 and derived_2 which contain class base_t and override a virtual function of an interface class.
When attempting to call the virtual function of one object I see that it is the function of the other object which is being called.
I also opened the map file and saw that the wrong method is the one being linked.
base.hpp:
#ifndef BASE_HPP
#define BASE_HPP
extern int globalFlag;
class base_t {
public:
struct callBack_t {
virtual void virtualFunction(void) = 0;
};
base_t(callBack_t& callBack)
: _callBack(callBack) {}
void run() { _callBack.virtualFunction(); }
callBack_t& _callBack;
};
#endif //BASE_HPP
derived_1.cpp:
#include "base.hpp"
class derivedCallBack_t : public base_t::callBack_t
{
public:
void virtualFunction(void) {
globalFlag = 1;
}
};
class derived_1_t
{
public:
derived_1_t(void);
derivedCallBack_t* _derivedCallBack;
base_t _base;
};
derived_1_t::derived_1_t(void):
_derivedCallBack(new derivedCallBack_t()),
_base(base_t(*_derivedCallBack))
{}
derived_2.cpp:
#include <iostream>
#include "base.hpp"
class derivedCallBack_t : public base_t::callBack_t
{
public:
void virtualFunction(void) {
globalFlag = 2;
}
};
class derived_2_t
{
public:
derived_2_t(void):
_derivedCallBack(new derivedCallBack_t())
, _base(base_t(*_derivedCallBack))
{}
derivedCallBack_t* _derivedCallBack;
base_t _base;
};
int globalFlag = 0;
int main()
{
derived_2_t derived = derived_2_t();
derived._base.run();
std::cout << "globalFlag " << globalFlag; //expecting globalFlag to be 2
}