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

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top