A question about private virtual function

S

sun1991

#include <iostream>
using namespace std;

class Base{
public:
void ToString(){
ToStringCore();
}
private:
virtual void ToStringCore(){
cout << "this is Base" << endl;
}
};

class Derived: public Base{};

int main(){
Derived d;
d.ToString();
}
 
T

Thomas Tutone

sun1991 said:
#include <iostream>
using namespace std;

class Base{
public:
void ToString(){
ToStringCore();
}
private:
virtual void ToStringCore(){
cout << "this is Base" << endl;
}
};

class Derived: public Base{};

int main(){
Derived d;
d.ToString();
}

d didn't call a private member function. d called Base::toString(),
which is a public member function. Base:toString() called
Base::ToStringCore(), which it is entitled to do because
Base::ToString() is a Base member function, and Base member functions
may call private Base member functions. Private member functions
wouldn't serve much purpose if they couldn't be called indirectly in
this way.

Best regards,

Tom
 
M

mlimber

Thomas said:
d didn't call a private member function. d called Base::toString(),
which is a public member function. Base:toString() called
Base::ToStringCore(), which it is entitled to do because
Base::ToString() is a Base member function, and Base member functions
may call private Base member functions. Private member functions
wouldn't serve much purpose if they couldn't be called indirectly in
this way.

Compare also the guidelines for access to virtual functions given by
Guru Sutter:

http://www.gotw.ca/publications/mill18.htm

Cheers! --M
 

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

Forum statistics

Threads
473,996
Messages
2,570,238
Members
46,826
Latest member
robinsontor

Latest Threads

Top