Domanda

Suppose following code is given.

class A
{
public:
   virtual void someMethod()
   {
      std::cout << "class A" << std::endl;
   }
};

class B : public A
{
public:
   ...
   virtual void someMethod() = 0;
   ...
};

Class B overrides someMethod virtual method with pure-virtual method. The purpose of doing this might be extension of existing class which is not allowed to modify in our case class A, but still having an abstract class B which has to be base class for some further classes.

According to MISRA-C++ Rule 10-3-3 : Code analyzer gives a warning : Pure virtual function overrides a non pure virtual function .

But I cannot find much details about the warning. What is the side effect of the above mentioned code ? What is the bad practice here ?


UPDATE : the standard is MISRA-C++ (C++98)

È stato utile?

Soluzione

I can't see any mystery here. The code analyser is likely checking your code against the MISRA standard, not the C++ 98 standard.

MISRA is a set of C/C++ coding standards for the automotive environment, which imposes further restrictions on what is supposedly legal/permitted by the language standard.

You ARE overriding with a pure virtual function a non pure virtual function, and apparently this is ok with the compiler but not with the MISRA rules.

That is to say, your program will compile and execute fine, and will be compliant with the language standard, but it might not be accepted by a customer that requires code review and compliance with the MISRA standard.

Altri suggerimenti

I'd say your code is valid as per standard:

§ 10.4

5 [ Note: An abstract class can be derived from a class that is not abstract, and a pure virtual function may override a virtual function which is not pure. —end note ]

The inheritance is backwards.

It has class A inherited by class B. B has the pure virtual function. I believe that you want the following code. It says the child classes of B must implement somemethod().

class B
{
public:
   ...
   virtual void someMethod() = 0;
   ...
};

class A : public B
{
public:
   virtual void someMethod()
   {
      std::cout << "class A" << std::endl;
   }
};
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top