Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pure virtual and inline definition

Tags:

c++

Consider:

struct device{
    virtual void switchon() = 0 {}
};

int main()
{

}

I wrote code similar to following and it gave an error:

pure-specifier on function-definition compilation terminated due to -Wfatal-errors.

When I asked him, he showed me the following quote from the standard:

A virtual function declared in a class shall be defined, or declared pure (10.4) in that class, or both; but no diagnostic is required (3.2).

I can't seem to understand what it means and I think this somehow is not relevant.

PS: If this is not the relevant quote, please guide me to the proper one so that I can have a better counterargument.

like image 727
Nivhus Avatar asked Oct 01 '10 02:10

Nivhus


People also ask

What is a pure virtual?

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.

What is difference between pure virtual and virtual?

A virtual function is a member function of base class which can be redefined by derived 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.

What are virtual and inline functions?

Inline virtual function in C++The main use of the virtual function is to achieve Runtime Polymorphism. The inline functions are used to increase the efficiency of the code. The code of inline function gets substituted at the point of an inline function call at compile time, whenever the inline function is called.

What is pure virtual function example?

A pure virtual function doesn't have the function body and it must end with = 0 . For example, class Shape { public: // creating a pure virtual function virtual void calculateArea() = 0; }; Note: The = 0 syntax doesn't mean we are assigning 0 to the function.


1 Answers

A pure virtual function may have a definition (out of class definition). That is completely optional. But what you are trying to do is plain wrong because

C++03 [Section 10.4/2] says:

[Note: a function declaration cannot provide both a pure-specifier and a definition —end note] [Example:

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

However you are free to write

struct device{
    virtual void switchon() = 0;
};

void device::switchon() { } // Definition {optional}

int main()
{

}
like image 156
Prasoon Saurav Avatar answered Oct 07 '22 20:10

Prasoon Saurav