I just spotted this in some code:
class Foo { [...] private: virtual void Bar() = 0; [...] }
Does this have any purpose?
(I am trying to port some code from VS to G++, and this caught my attention)
C++ has access control, but not visibility control. This means that private functions are visible but not accessible. A private virtual function can be overridden by derived classes, but can only be called from within the base class.
Virtual functions, in their view, should never be public, because they define the class' interface, which must remain consistent in all derived classes. Protected and private virtuals define the class' customizable behavior, and there is no need to make them public.
Virtual methods cannot be private in C#. All the virtual methods must have to provide the body definition in C#. A virtual method cannot be static or abstract in C#. The virtual modifier cannot be used when overriding the virtual method i.e. virtual modifiers cannot be used with the override keyword.
The Virtual function cannot be private, as the private functions cannot be overridden. A virtual function or method also cannot be final, as the final methods also cannot be overridden. Static functions are also cannot be overridden; so, a virtual function should not be static.
See this Herb Sutter article as to why you'd want to do such a thing.
This is a pure virtual function that happens to be private. This makes it so that a derived class must implement the method. In this case Bar.
I think you may be confused b/c this is done to create "interfaces" in C++ and a lot of times people think of these as public. There are cases where you may want to define an interface that is private where a public method uses those private methods in order to ensure the order of how they are called. (I believe this is called the Template Method)
For a relatively bad example :)
class RecordFile { public: RecordFile(const std::string &filename); void process(const Record &rec) { // Call the derived class function to filter out // records the derived instance of this class does // not care about if (filterRecord(rec)) { writeRecordToFile(rec); } }; private: // Returns true if the record is of importance // and should be kept virtual bool filterRecord(const Record &rec) = 0; void writeRecordToFile(const Record &rec); };
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With