Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Body for pure virtual function in C++17?

Tags:

I tried to write an pure virtual function in Base class, and i give it an body near the definition as it shown in the code bellow, as I know i should get an compile error, But everything worked fine. Is it something new that come with C++17 ? (I used visual studio 2017)

class Base {
public:
virtual void virtual_func() { std::cout << "This a virtual function from BASE" << std::endl; };
virtual void pure_func() = 0 { std::cout << "This a PURE virtual function from BASE" << std::endl; };
};

Thanks

like image 288
Aniss Be Avatar asked Apr 26 '17 01:04

Aniss Be


People also ask

Can pure virtual function have a body?

Pure virtual functions (when we set = 0 ) can also have a function body.

What is a pure virtual function in C?

A pure virtual function or pure virtual method is a virtual function that is required to be implemented by a derived class if the derived class is not abstract. Classes containing pure virtual methods are termed "abstract" and they cannot be instantiated directly.

What is the syntax of pure virtual function?

¶ Δ A pure virtual function is a function that must be overridden in a derived class and need not be defined. A virtual function is declared to be “pure” using the curious =0 syntax.

Can we define pure virtual function in base class?

A pure virtual function is a member function of base class whose only declaration is provided in base class and should be defined in derived class otherwise derived class also becomes abstract. Classes having virtual functions are not abstract. Base class containing pure virtual function becomes abstract.


1 Answers

The pure virtual cannot be used together with a definition. This was true in C++11, and in C++14:

10.4/2:...
[ Note: A function declaration cannot provide both a pure-specifier and a definition — end note ] [ Example:

struct C {
virtual void f() = 0 { }; // ill-formed
};

The same statement (under section 13.4/2 this time) is still true for C++17 (N4659).

So if your compiler accept this code, it's certainly a bug (gcc 7.1 doesesn't)

like image 79
Christophe Avatar answered Sep 23 '22 10:09

Christophe