Private Virtual Functions


For the latest documentation on Visual Studio 2017 RC, see Visual Studio 2017 RC Documentation.

The way private virtual functions are handled in derived classes has changed from Managed Extensions for C++ to Visual C++.

In Managed Extensions, the access level of a virtual function does not constrain its ability to be overridden within a derived class. In the new syntax, a virtual function cannot override a base class virtual function that it cannot access. For example:

__gc class MyBaseClass {  
   // inaccessible to a derived class   
   virtual void g();  
__gc class MyDerivedClass : public MyBaseClass {  
   // okay in Managed Extensions; g() overrides MyBaseClass::g()  
   // error in new syntax; cannot override: MyBaseClass::g() is inaccessible …  
   void g();  

There is no real mapping of this sort of design onto the new syntax. One simply has to make the base class members accessible – that is, non-private. The inherited methods do not have to bear the same access. In this example, the least invasive change is to make the MyBaseClass member protected. This way the general program's access to the method through MyBaseClass is still prohibited.

ref class MyBaseClass {  
   virtual void g();  
ref class MyDerivedClass : MyBaseClass {  
   virtual void g() override;  

Note that the absence of the explicit virtual keyword in the base class, under the new syntax, generates a warning message.

Member Declarations within a Class or Interface (C++/CLI)
Member Visibility