In the main() function below, d is a base class pointer (of type A) which points to a derived class (of type B). Yet when the member function f(int) is called on this pointer, i.e. d->f(1), the compiler calls the non-virtual function in the base class A (labelled #2), i.e.
void f(int n) const { std::cout << n; }
Why? I was expecting that since there is also a virtual function in the base class A
virtual void f(int n) { std::cout << n; }
one of the two functions f(int) in the derived class B would be called. Where am I going wrong?
class A
{
public:
A() {}
public:
virtual void f(int n) { std::cout << n; } // #1
virtual ~A() { }
void f(int n) const { std::cout << n; } // #2 this function is called when d->f(1) is executed in main()
};
class B
: public A
{
public:
void f(int n) { std::cout << n; } // #3
void f(int n) const { std::cout << n; } // #4
};
int main()
{
B b;
const A* d = &b;
d->f(1); // this calls function #2 above - why?
std::cout << std::endl;
return 0;
}
dis aconst A*so operations cannot be done ondthat logically change the object it points to. Sod->f(1)needs to call theconstversion off(), as only that function promises not to change the object pointed to byd. Remove theconstversions off()from classA, and the result will be a diagnostic from your compiler due to attempt to call anon-const` member function of aconstobject. The facts thatbis notconstor that one version off()isvirtualare irrelevant - theconstqualifier when declaringdmeans thatdcannot be used to changeb. - Peterfso that they are easier to refer to. If this is acceptable, I'll update my answer as well to use those labels. - cigien