Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

The output of the code snippet is not what i expected

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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 this a pointer to Visitable instead of A

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).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading