lundi 18 octobre 2021

Understand const correctess with pointers in C++

I have the following test code:

class A
{
    public:
    void funcA()
    {
        std::cout << "banana" << std::endl;
    }
};

class B
: public A
{
    public:
    A t;

    void funcB() const
    {
       t.funcA();
    }
};

int main(int argCount, char *args[])
{
   B tst;
   tst.funcB();
}

Where funcA does not have a constdefinition and funcB has a const definition.

When compiling the code, I get the error:

passing ‘const A’ as ‘this’ argument discards qualifiers [-fpermissive]

This should happen because I am calling inside a const function a non-const function.

However, when I do:

class B
: public A
{
    public:
    A* t;

    void funcB() const
    {
       t->funcA();
    }
};

The code compiles and works. Why is that? I am just compiling with g++ -g main.cpp, and I missing flags for this? or is this behavior to be expected?

Aucun commentaire:

Enregistrer un commentaire