My favorite interview question (private pure virtual function)

One of my favorite interview questions is about a private pure virtual function.


class Foo {
virtual void func() = 0;

Question: Is it allowed to declare a function as private pure virtual? If yes, explain a practical purpose. If no, explain a reason C++ does not allow it.

Depending on an interviewee’s C++ skill, she would have a different answer.

Answer 1: It’s not allowed. A private function is not visible to derived classes and they cannot override it. It’s not valid C++ because every pure virtual function must be overridden to instantiate the object.

She probably read a C++ book, and understand the difference between private and protected. However, she misunderstands "not callable" as "not visible".

Answer 2. It’s allowed but there is no practical purpose. A pure virtual function is used to declare a interface without implementation. Therefore, it does not make sense to declare it as private.

She probably studied Java or COM, and has some experience of interface based design in C++. Very good. However, it’s not enough.

Correct Answer. It’s allowed and often used to implement the template method design pattern.


About Moto

Engineer who likes coding
This entry was posted in C++. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s