I don’t understand why this code snippet using an altered version of the visitor patters is always printing the log V instead of A. Compiled using c++11 version.
#include <iostream>
using namespace std;
class A;
class B;
class Visitable;
class Visitor
{
public:
void visit(const A& a)
{
std::cout << "A" << std::endl;
}
void visit(const Visitable& v)
{
std::cout << "V" << std::endl;
}
void visit(const B& b)
{
std::cout << "B" << std::endl;
}
};
class Visitable
{
public:
virtual void Accept(Visitor* visitor)
{
visitor->visit(*this);
}
};
class A : public Visitable
{
};
class B : public Visitable
{
};
int main()
{
Visitor* v = new Visitor();
A* a = new A();
a->Accept(v); // IT PRINTS V INSTEAD OF A.
return 0;
}
I executed the code snipped, i was expecting to see the log A in the output console.
>Solution :
The type of *this is Visitable which matches the type of the parameter in the member function void Visitor::visit(const Visitable&) so that it is the only viable option and hence selected.
That is, the other two member function void Visitor::visit(const A&) and void Visitor::visit(const B&) are not viable since the passed argument in the call visitor->visit(*this); is of type Visitable while the parameter type in these member functions is const A& and const B& respectively.
why is
thisa pointer to Visitable instead ofA
Because as per the standard, inside the body of a non-const non-static member function func of a class X, the type of pointer this is X*. This means that *this is X. This can be seen(pun intended) from this:
The expression this is a prvalue expression whose value is the address of the implicit object parameter (object on which the non-static member function is being called).