Search code examples
c++linuxinheritancepointerscasting

Calling Virtual Function of Parent


#include <linux/input.h>
#include <string.h>

#include <gtest/gtest.h>
#include <string>
class Parent{
public:
    Parent(){
    }
    virtual std::string GetString()
    {
        int amount = 1;
        input_event ev[amount];
        ev[0].code = BTN_9;
        ev[0].value = 1;
        char* temp = reinterprt_cast<char*>(ev);
        std::string msg(temp, sizeof(ev) * amount);
        return msg;
    }
};
class Child : public Parent
{
public:
    Child(){
    }
    virtual std::string GetString()
    {
        int amount = 1;
        input_event ev[amount];
        ev[0].code = BTN_9;
        ev[0].value = 1;
        char* temp = reinterpret_cast<char*>(ev);
        std::string msg(temp, sizeof(ev) * amount);
        return msg;
    }

};

class Child2 : public Parent
{
public:
    Child2(){
    }
    virtual std::string GetString()
    {
        std::string temp(Parent::GetString());
        return temp;
    }

};

TEST(CastToString, test)
{
    Parent parent = Parent();
    Child child1 = Child();
    Child2 child2 = Child2();
    std::string pString(parent.GetString());
    std::string c1String(child1.GetString());
    std::string c2String(child2.GetString());
    EXPECT_EQ(pString, c1String);
    EXPECT_EQ(pString, c2String);
}

I just copied in the whole sample. The problem lies at the call of Child2s GetString function. It always returns different values hence i assume, there is some allocation problem, but i cant figure it out.


Solution

  • I think the error is here

      std::string msg(temp, sizeof(ev) * amount);
    

    should be

      std::string msg(temp, sizeof(ev[0]) * amount);
    

    (both places).

    Because the array size was wrong you were getting extra garbage bytes in your string, so they didn't compare equal.