C++ Add non-virtual static method in interface is normal? - c++

I thought interface can only include pure virtual functions in C++. However, recently my college showed me the following code:
class IAddition {
public:
virtual bool MethodA() = 0;
static bool StaticMethodA(IAddition* interface) {
return interface->MethodA();
}
static std::string GetStr() {
return "A";
}
};
The interface can be compiled but I feel the code weird. I can't understand what is a static method of an interface? Is this very normal in C++ programs?

I thought interface can only include pure virtual functions in C++
There is no such requirement imposed by the C++ standard.
Is this very normal in C++ programs?
Yes(assuming by normal you mean well-formed), this is a valid C++ program. We're allowed to use virtual member function with static as well as non-static member functions within a class.

As blankettripod point out in comment and Jason Liam in other answear C++ language do not have interface concept. So purely from C++ standard perspective this is fine.
But in many best C++ practices interface means:
class or a struct without any fields and only with public pure virtual functions inside (except for destructor which must be implemented and should be virtual).
See also Cpp Core Guidelines I.25: Prefer empty abstract classes as interfaces to class hierarchies.
So your IAddition fails this definition because of this static methods.
Many developers will not have problem with that.
On other hand in many projects where coding standard rules are more strict and respected, this is no longer an interface and should be fixed. There are many rationales, for example if this API is ported to other languages (like Java or C# where interfaces are part of language features) this extra methods will be a real technical problem.

Related

When does it make sense to use an abstract class

I'm transitioning from c to c++ and of course, OOP which is proving more difficult than expected. The difficulty isn't understanding the core mechanics of classes and inheritance, but how to use it. I've read book on design patterns but they only show the techniques and paint a vague picture of why the techniques should be used. I am really struggling to find a use for abstract classes. Take the code below for example.
class baseClass {
public:
virtual void func1() = 0;
virtual void func2() = 0;
};
class inhClass1 : baseClass {
public:
void func1();
void func2();
};
class inhClass2 : baseClass{
public:
void func1();
void func2();
};
int main() {}
I frequently see abstract classes set up like this in design books. I understand that with this configuration the inherited classes have access to the public members of the base class. I understand that virtual functions are placeholders for the inherited classes. The problem is I still don't understand how this is useful. I'm trying to compare it to overloading functions and I'm just not seeing a practical use.
What I would really like is for someone to give the simplest example possible to illustrate why an abstract class is actually useful and the best solution for a situation. Don't get me wrong. I'm not saying there isn't a good answer. I just don't understand how to use them correctly.
Abstract classes and interfaces both allow you to define a method signature that subclasses are expected to implement: name, parameters, exceptions, and return type.
Abstract classes can provide a default implementation if a sensible one exists. This means that subclasses do not have to implement such a method; they can use the default implementation if they choose to.
Interfaces do not have such an option. Classes that implement an interface are required to implement all its methods.
In Java the distinction is clear because the language includes the keyword interface.
C++ interfaces are classes that have all virtual methods plus a pure virtual destructor.
Abstract classes and interfaces are used when you want to decouple interface from implementation. They're useful when you know you'll have several implementations to choose from or when you're writing a framework that lets clients plug in their own implementation. The interface provides a contract that clients are expected to adhere to.
One use of abstract classes is to be able to easily switch between different concrete implementations with minimal changes to your code. You do this by declaring a reference variable to the base class type. The only mention of the derived class is during creation. All other code uses the base class reference.
Abstract classes are used to provide abstract representation of some concept you want to implement hiding the details.
For example let's say I want to implement File system interface :-
At abstract level what I can think of?
class FileSystemInterface
{
virtual void openFile();
virtual void closeFile();
virtual void readFile();
virtual void writeFile();
};
At this point of time I am not thinking of anything specific like how they will be handled in windows or linux rather I am focusing on some abstract idea.

Is it an abstract class or a pure virtual (interface)?

It might be a silly question but I never saw a question about it or read about it.
Imagine that we have this:
class Numeric
{
public:
virtual ~Numeric() {}
virtual int getNumeric() const = 0;
};
This is considered an interface.
And now I insert an enumerator (It can be something else, like a typedef, etc.)
class Numeric
{
public:
enum Numbers
{
One,
Two,
};
virtual Numbers getNumeric() const = 0;
};
Still being an interface or it is now considered an abstract class?
As I said, it might be silly but I really wonder to know that.
If you are looking for an official answer, then I'm afraid there is none.
The draft of the C++11 standard I am having here merely says [10.4 class.abstract]:
An abstract class can also be used to define an interface for which
derived classes provide a variety of implementations.
All other instances of the word "interface" in the entire ~1300 pages PDF only refer to generic programming or other things not related to OOP or abstract classes.
For example this one here [24.2.1 iterator.requirements.general]:
Most of the library’s algorithmic templates that operate on data
structures have interfaces that use ranges.
This obviously has nothing to do with abstract classes.
Bjarne Stroustrup himself, if you accept his words as "half-official", doesn't really help you in this regard, either. Quoting from the glossary on his homepage:
abstract class - a class defining an interface only; used as a base
class.
You will have to live with the fact that the C++ language itself as well as C++ developers and experts use the word "interface" as a superset for "abstract class". Unlike e.g. in Java, where interfaces are an actual language element with its own interface keyword, there is no such thing in C++.
Everything else is opinion-based.
Your second class Numeric is an interface.
If a class has one or more pure virtual functions, then this class is called an "abstract class".
Generally, if all of a classes' functions are pure virtual functions, then this class is called an "interface".
C++ does not have an explicit interface concept, so the above two classes are called the interface or abstract class, somewhat interchangably.
In my opinion, your second class can be considered an interface. I don't think there is a standard which defines interfaces in C++. However in languages which have interfaces, for example, Java, you can usually have enums defined inside an interface.
I would consider a class with no implementation to be an interface.

Difference between interface and polymorphism [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 9 years ago.
Improve this question
I was reading an online excerpt from a C++ book on polymorphism and interfaces.
The book made a distinction between polymorphism and interfaces, and specified how to implement them in C++. However, I was always under the idea that interfaces in C++ (implemented using a base class with pure virtual functions) were nothing more than an application of polymorphism.
I would like to know the clear distinction between polymorphism and interfaces because the excerpt confused me.
Polymorphism is the abstract concept of dealing with multiple types in a uniform manner, and interfaces are a way to implement that concept. Code that interacts with an interface can interact with any type that provides that interface.
Note that C++ has (at least) two forms of polymorphism: dynamic (i.e. run-time) polymorphism via interfaces formally defined by virtual functions, and static (i.e. compile-time) polymorphism via interfaces informally defined by the use of template parameters.
Typical C++ interfaces make use of virtual functions and polymorphism to provide the actual implementation. But polymorphism covers many other things, which is "not interfaces".
An interface is a base-class that can be used to a class that is passed back to something that accepts that interface. In some cases, a class may provide more than one interface:
class MyClass: public InterfaceGUI, InterfaceAudio
{
....
};
here, MyClass provides a class that interfaces both with the GUI and the Audio interfaces. This is a one case of multiple inheritance.
On the other hand:
class Animal
{
int numLegs;
public:
Animal(int nLegs): numLegs(nLegs) {}
};
class Dog : public Animal
{
Dog() : Animal(4) { }
};
here Animal is not a pure interface class, since it implements some functionality, and this is generally not a good design for an interface.
What i understood from the concept of polymorphism and Interface is as follows:
Polymorphism :
Polymorphism is nothing but having more than one form(As per all books).
But As per the Object orientation when you relate it with the real life You will get to know that Polymorphism is nothing but having more than one form with same name or some other Quality but have one's own Patent quality which no one have.
As per the programming:
A function with same name But different arguments (Compile time Polymorphism) and a Virtual function used for Runtime Polymorphism As explained here
Check this Example
Interface
An interface describes the behavior or capabilities of a C++ class without committing to a particular implementation of that class.
The C++ interfaces are implemented using abstract classes and these abstract classes should not be confused with data abstraction which is a concept of keeping implementation details separate from associated data.
For this purpose we use Pure Virtual function
For Reference you can go through this Link
And for example you can use explanation by Mats Petersson
Hope this will help you to understand the basic senario.

Use-cases of pure virtual functions with body?

I recently came to know that in C++ pure virtual functions can optionally have a body.
What are the real-world use cases for such functions?
The classic is a pure virtual destructor:
class abstract {
public:
virtual ~abstract() = 0;
};
abstract::~abstract() {}
You make it pure because there's nothing else to make so, and you want the class to be abstract, but you have to provide an implementation nevertheless, because the derived classes' destructors call yours explicitly. Yeah, I know, a pretty silly textbook example, but as such it's a classic. It must have been in the first edition of The C++ Programming Language.
Anyway, I can't remember ever really needing the ability to implement a pure virtual function. To me it seems the only reason this feature is there is because it would have had to be explicitly disallowed and Stroustrup didn't see a reason for that.
If you ever feel you need this feature, you're probably on the wrong track with your design.
Pure virtual functions with or without a body simply mean that the derived types must provide their own implementation.
Pure virtual function bodies in the base class are useful if your derived classes wants to call your base class implementation.
One reason that an abstract base class (with a pure virtual function) might provide an implementation for a pure virtual function it declares is to let derived classes have an easy 'default' they can choose to use. There isn't a whole lot of advantage to this over a normal virtual function that can be optionally overridden - in fact, the only real difference is that you're forcing the derived class to be explicit about using the 'default' base class implementation:
class foo {
public:
virtual int interface();
};
int foo::interface()
{
printf( "default foo::interface() called\n");
return 0;
};
class pure_foo {
public:
virtual int interface() = 0;
};
int pure_foo::interface()
{
printf( "default pure_foo::interface() called\n");
return 42;
}
//------------------------------------
class foobar : public foo {
// no need to override to get default behavior
};
class foobar2 : public pure_foo {
public:
// need to be explicit about the override, even to get default behavior
virtual int interface();
};
int foobar2::interface()
{
// foobar is lazy; it'll just use pure_foo's default
return pure_foo::interface();
}
I'm not sure there's a whole lot of benefit - maybe in cases where a design started out with an abstract class, then over time found that a lot of the derived concrete classes were implementing the same behavior, so they decided to move that behavior into a base class implementation for the pure virtual function.
I suppose it might also be reasonable to put common behavior into the pure virtual function's base class implementation that the derived classes might be expected to modify/enhance/augment.
One use case is calling the pure virtual function from the constructor or the destructor of the class.
The almighty Herb Sutter, former chair of the C++ standard committee, did give 3 scenarios where you might consider providing implementations for pure virtual methods.
Gotta say that personally – I find none of them convincing, and generally consider this to be one of C++'s semantic warts. It seems C++ goes out of its way to build and tear apart abstract-parent vtables, then briefly exposes them only during child construction/destruction, and then the community experts unanimously recommend never to use them.
The only difference of virtual function with body and pure virtual function with body is that existence of second prevent instantiation. You can't mark class abstract in c++.
This question can really be confusing when learning OOD and C++. Personally, one thing constantly coming in my head was something like:
If I needed a Pure Virtual function to also have an implementation, so why make it "Pure" in first place ? Why not just leaving it only "Virtual" and have derivatives, both benefit and override the base implementation ?
The confusion comes to the fact that many developers consider the no body/implementation as the primary goal/benefit of defining a pure virtual function. This is not true!
The absence of body is in most cases a logical consequence of having a pure virtual function. The main benefit of having a pure virtual function is defining a contract: By defining a pure virtual function, you want to force every derivative to always provide their own implementation of the function. This "contract aspect" is very important especially if you are developing something like a public API. Making the function only virtual is not so sufficient because derivatives are no longer forced to provide their own implementation, therefore you may loose the contract aspect (which can be limiting in the case of a public API).
As commonly said :
"Virtual functions can be overrided, Pure Virtual functions must be overrided."
And in most cases, contracts are abstract concepts so it doesn't make sense for the corresponding pure virtual functions to have any implementation.
But sometimes, and because life is weird, you may want to establish a strong contract among derivatives and also want them to somehow benefit from some default implementation while specifying their own behavior for the contract. Even if most book authors recommend to avoid getting yourself into these situations, the language needed to provide a safety net to prevent the worst! A simple virtual function wouldn't be enough since there might be risk of escaping the contract. So the solution C++ provided was to allow pure virtual functions to also be able to provide a default implementation.
The Sutter article cited above gives interesting use cases of having Pure Virtual functions with body.

How to design a C++ API for binary compatible extensibility

I am designing an API for a C++ library which will be distributed in a dll / shared object. The library contains polymorhic classes with virtual functions. I am concerned that if I expose these virtual functions on the DLL API, I cut myself from the possibility of extending the same classes with more virtual functions without breaking binary compatibility with applications built for the previous version of the library.
One option would be to use the PImpl idiom to hide all the classes having virtual functions, but that also seem to have it's limitations: this way applications lose the possibility of subclassing the classes of the library and overriding the virtual methods.
How would you design a API class which can be subclassed in an application, without losing the possibility to extend the API with (not abstract) virtual methods in a new version of the dll while staying backward binary compatible?
Update: the target platforms for the library are windows/msvc and linux/gcc.
Several months ago I wrote an article called "Binary Compatibility of Shared Libraries Implemented in C++ on GNU/Linux Systems" [pdf]. While concepts are similar on Windows system, I'm sure they're not exactly the same. But having read the article you can get a notion on what's going on at C++ binary level that has anything to do with compatibility.
By the way, GCC application binary interface is summarized in a standard document draft "Itanium ABI", so you'll have a formal ground for a coding standard you choose.
Just for a quick example: in GCC you can extend a class with more virtual functions, if no other class inherits it. Read the article for better set of rules.
But anyway, rules are sometimes way too complex to understand. So you might be interested in a tool that verifies compatibility of two given versions: abi-compliance-checker for Linux.
There is an interesting article on the KDE knowledge base that describes the do's and don'ts when aiming at binary compatibility when writing a library: Policies/Binary Compatibility Issues With C++
C++ binary compat is generally difficult, even without inheritance. Look at GCC for example. In the last 10 years, I'm not sure how many breaking ABI changes they've had. Then MSVC has a different set of conventions, so linking to that with GCC and vice versa can't be done... If you compare this to the C world, compiler inter-op seems a bit better there.
If you're on Windows you should look at COM. As you introduce new functionality you can add interfaces. Then callers can QueryInterface() for the new one to expose that new functionality, and even if you end up changing things a lot, you can either leave the old implementation there or you can write shims for the old interfaces.
I think you misunderstand the problem of subclassing.
Here is your Pimpl:
// .h
class Derived
{
public:
virtual void test1();
virtual void test2();
private;
Impl* m_impl;
};
// .cpp
struct Impl: public Base
{
virtual void test1(); // override Base::test1()
virtual void test2(); // override Base::test2()
// data members
};
void Derived::test1() { m_impl->test1(); }
void Derived::test2() { m_impl->test2(); }
See ? No problem with overriding the virtual methods of Base, you just need to make sure to redeclare them virtual in Derived so that those deriving from Derived know they may rewrite them too (only if you wish so, which by the way is a great way of providing a final for those who lack it), and you may still redefine it for yourself in Impl which may even call the Base version.
There is no problem with Pimpl there.
On the other hand, you lose polymorphism, which may be troublesome. It's up to you to decide whether you want polymorphism or just composition.
If you expose the PImpl class in a header file, then you can inherit from it. You can still maintain backward portability since the external classes contains a pointer to the PImpl object. Of course if the client code of the library isn't very wise, it could misuse this exposed PImpl object, and ruin the binary backward compatibility. You may add some notes to warn the user in the PImpl's header file.