Why polymorph fails when virtual function is decleared private in base class and public in derived c

F

Fred

I've got the following code:

#include <iostream>


class Base{
private:
virtual void f(int) { std::cout << "f in Base" << std::endl; }
};

class Derived : public Base{
public:
virtual void f(int) { std::cout << "f in Derived" << std::endl; }
};


int main(void)
{
Base base;
Derived derived;

Base* p = &derived;
p->f(2);

return 1;
}

In base class f is decleared as private member function, and the
compiler complains that pointer p couldn't access private member in
base. It's clear that polymorph fails here. Why does it happen? Thanks
for help.
 
A

Alf P. Steinbach

* Fred:
I've got the following code:

#include <iostream>


class Base{
private:
virtual void f(int) { std::cout << "f in Base" << std::endl; }
};

class Derived : public Base{
public:
virtual void f(int) { std::cout << "f in Derived" << std::endl; }
};


int main(void)
{
Base base;
Derived derived;

Base* p = &derived;
p->f(2);

return 1;
}

In base class f is decleared as private member function, and the
compiler complains that pointer p couldn't access private member in
base.
Right.


It's clear that polymorph fails here.

Polymorphism doesn't fail.

Why does it happen?

The statically known type (the type known at compile time) is Base. And
in Base, that member function is private.
 
R

Ron Natalie

The dynamic type of the object is only tested at the last step
in the selection of the virtual function. Everything else uses
the static type. The call is done roughly as follows:

1. The name of the function is looked up in the calling scope.
2. Overloads for that name are checked to find the best match.
3. The protection for that overload is checked.
4. Then IF the function is virtual, the final overriding function
is called

The difference between static and dynamic type only comes into play
at step 4.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top