Pregunta

Consider the following code, in this case output is:

f non const
g const

It is a bit confusing because someClass is calling non const function for const data member from its const function:

#include <iostream>
using namespace std;

class Inner
{
public:
    void f() const { cout<< "f const" <<endl; }
    void f() { cout<< "f non const" <<endl; }
};

class someClass
{
    Inner * const obj2;
public:
    someClass():obj2(){}
    void g() {obj2->f(); cout<< "g non const" <<endl; }
    void g() const {obj2->f(); cout<< "g const" <<endl; }

};

int main()
{
    const someClass a;
    a.g();
}

Why is someClass calling non const function in this case?

¿Fue útil?

Solución 2

Here is the answer:

obj2 in class someClass is a type of Inner * const, which means that the pointer is const, not the data itself, thus it is calling a non const function.

To get the expected output, the obj2 must be declared in this way:

Inner const * obj2;

Otros consejos

I guess you're asking why void Inner::f() is called. This is because you have a const pointer to non-const Inner:

Inner * const obj2;

If you want a pointer to const Inner, then you need

const Inner * obj2;

or

Inner const * obj2;

and if you want a const pointer to const inner,

const Inner * const obj2;

and I'll let you figure out the other alternative.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top