Overload method / operator with inheritance will not work

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

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

here is an example of compiled 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);
}

The compiler tries to call the (operator ()) method without the const attribute, while the const method is available in the ConstA base class. I do not know why I get such an error.

+3
source share
2 answers

const , , . using ConstA::operator(), A.

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

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

, .

+10

, ++ hiding , ConstA:: operator() :

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();
}

, B:: foo() ! , , A. , ConstA

+2

All Articles