开发者

Overload method/operator with inheritance won't work

开发者 https://www.devze.com 2023-03-10 00:42 出处:网络
I wrote code when one class has only constant access to its content, and that was inherited by other class which provides the same method, but with normal access to its members. When I try to compile

I wrote code when one class has only constant access to its content, and that was inherited by other class which provides the same method, but with normal access to its members. When I try to compile it by gcc I get following error code:

error: passing ‘const A’ as ‘this’ argument of ‘void A::operator()()’ discards qualifiers 

here is sample compilable code:

#include<stdio.h>

class ConstA {
    public:
        void operator()() const {
            printf("const\n");
        }
};

class A : 开发者_高级运维public ConstA {
    public:
        void operator()() {
            printf("non-const\n");
        }
};

class B : public A {
};

void f(const A& a) {
    a();
}

int main() {
    B b;
    f(b);
}

Compiler tries to invoke method(operator ()) without const attribute, while const method is accessible in base ConstA class. I do not know why I get this kind of error.


The const method is not accessible, the base class version is hidden by the derived class version, an annoying problem. You need using ConstA::operator() to bring it into the scope of A.

class A : public ConstA{
public:
  using ConstA::operator();

  void operator()(){
    printf("non-const\n");
  }
};

For further reading, look at this question of mine, which has some good explanations.


it is because C++ uses hiding on overloading, so after overloading, ConstA::operator() is NOT accessable
consider the following program:

class A {
public:
    void foo() { cout << "A" << endl; }
};
class B : public A {
public:
    void foo(int x) { cout << "B" << endl; }
};
int main() {
    B b;
    b.foo();
}

this one will also generate a compile error, because B::foo() is hidden! to envoke it you'll have to explicitly cast to A.
so in your example, you'll have to explicitly cast to ConstA

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号