C ++ "virtual" keyword placement

When I wrote the interface in Visual Studio 2015, I noticed some strange behavior. Normally, placing the keyword "virtual" in front of a function identifier does not matter, but if it is placed after a pointer or reference, it complains. See the following:

class B {}; class A { virtual B fun1a(); // OK B virtual fun1b(); // OK virtual B& fun2a(); // OK B& virtual fun2b(); // ERROR, "expected an identifier" virtual B* fun3a(); // OK B* virtual fun3b(); // ERROR, "expected an identifier" virtual std::unique_ptr<B> fun4a(); // OK std::unique_ptr<B> virtual fun4b(); // OK }; 

Why is this?

And, obviously, I can completely avoid errors by always setting the virtual keyword first, but I would like to write function descriptions as follows:

 foo const & // return value and relevant keywords on one line virtual bar( const baz &a ) const // function identifier, arguments, and relevant keywords on another line { /* method implementation */ } 

Alas, this is not possible for functions that return a link or pointer ...

Is this syntax error linguistic or visual studio localized?

+5
source share
2 answers

Have you considered using return types ? They will allow you to achieve your goal of putting the return type in your line:

 #include <memory> class B {}; class A { virtual auto fun1a() -> B; virtual auto fun1a() const -> B; virtual auto fun2a() -> B&; virtual auto fun2a() const -> B&; virtual auto fun2ac() -> B const&; virtual auto fun2ac() const -> B const&; virtual auto fun3b() -> B*; virtual auto fun3b() const -> B*; virtual auto fun3bc() -> B const*; virtual auto fun3bc() const -> B const*; virtual auto fun4a() -> std::unique_ptr<B>; virtual auto fun4a() const -> std::unique_ptr<B>; }; 

The caveat is that if you use final or override , then you put them after the return type:

 virtual auto fun3bc() const -> B const* final; 

Keep this in mind, however, that such an encoding convention (placing final or override on your own line) is very unusual. Just because C ++ allows you to use it, this is not necessarily a good idea.

+2
source

try it

 baz const // return value and relevant keywords on one line virtual &foo::bar( arg a, arg b ) const // function identifier, arguments, and relevant keywords on another line { /* method implementation */ } 
+1
source

Source: https://habr.com/ru/post/1267276/


All Articles