Let's assume you have an base class for the different states of a State Machine that has methods for different inputs like mouse, keyboard, joystick, etc. Now not every derived state is going to use all possible types of inputs. If the base class methods are pure virtual every derived state class needs to always implement every single one of them. To avoid this i declared them with an empty body in the base class and just override the ones that are used by the particular derived class. In case the class doesn't use a certain input type the empty base class method get's called. I am storing the currentState in a base class pointer and just feed it with the input without having to know which particular derived state it actually is to avoid unnessecary casts.
class Base
{
public:
virtual void keyboardInput() {}
virtual void mouseInput() {}
};
class Derived : public Base
{
public:
void keyboardInput()
{
// do something
}
// Derived doesnt use mouseInput so it doesn't implement it
};
void foo(Base& base)
{
base.keyboardInput();
base.mouseInput();
}
int main()
{
Derived der;
foo(der);
}
Is this considered a good practice?
Your question is opinion based, but I'd rather follow this approach to use an interface:
struct IBase {
virtual void keyboardInput() = 0;
virtual void mouseInput() = 0;
virtual ~IBase() {}
};
class Base : public IBase {
public:
virtual void keyboardInput() override {}
virtual void mouseInput() override {}
};
class Derived : public Base {
public:
void keyboardInput() override {
// do something
}
// Derived doesnt use mouseInput so it doesn't implement it
};
int main() {
std::unique_ptr<IBase> foo = new Derived();
foo->keyboardInput();
foo->mouseInput();
return 0;
}
Some arguments why that's better practice added from the comments:
The idea is that interface should contain as little assertions as possible, making it less likely to change, making it more dependable for those who inherit from it. Implementing the methods, albeit empty, is already an assertion, however small.
It would be less pain for refactorings coming later, which introduce more interfaces with multiple inheritance.
It really depends on what you want from the methods. When declaring an interface, usually the methods are left pure virtual because they are required to be implemented for the class to work at all. Marking them pure virtual signals "You have to implement this.".
However, sometimes there are methods that may do nothing and it's valid for all possible implementations for them to do nothing. It is not very common, but it is possible.
I don't think that your interface is the case though, and you should follow #πάντα ῥεῖ's answer. Or do it through multiple inheritance:
class MouseInput {
public:
virtual void mouseInput() = 0;
}
class KeyboardInput {
public:
virtual void keyboardInput() = 0;
}
class Derived : public KeyboardInput
{
public:
virtual void keyboardInput() override
{
// do something
}
};
class AllInput : public KeyboardInput, public MouseInput
{
public:
virtual void keyboardInput() override
{
// do something
}
virtual void mouseInput() override
{
// do something
}
};
That has the benefit that you can have methods that explicitly say that they work with one kind of input:
void doSomethingMouseIsh(MouseInput* input);
The disadvantage is that methods that combine mouse and keyboard input get weird unless you have InterfaceAllInput as interface and use it for all "all input methods"
Final note: as long as you try to write clean code, considering each use case is more important than some best practices.
If you going to be strict about it this does violate ISP (https://en.wikipedia.org/wiki/Interface_segregation_principle) as your forcing a subclass to depend on a method it doesn't use - but generally its not too bad in practice if the alternative adds more complexity.
Related
In C++ is it reasonable having an interface class inherits from a concrete class? Is this bad deign smell?
I have an interface which defines a behaviour, and a inherited class which defines an implementation.
Now I have another class and I want to state "Whoever inherits from this class need to specify behavior X, and defines this behavior Y which alread has a valid default implementation".
Is it correct practice this kind of implementation? I'm confused about this abstract/concrete mixing.
class IBase
{
public:
virtual ~IBase(){}
virtual void method1() = 0;
}
class ConcreteBase : IBase
{
public:
ConcreteBase(){}
void method1() override { // some impl; }
}
class ISpecialized : ConcreteBase
{
public:
// Here I don't need virtual destructor
void method2() = 0;
}
class ConcreteSpecialized : ISpecialized
{
public:
ConcreteSpecialized(){}
void method2() override { // some impl. }
}
Instead of having ISpecialized extend IBase, you should consider having it stand on its own. Then you can use multiple inheritance to make your concrete class derive from both interfaces.
class ISpecialized
{
public:
~ISpecialized(){}
void method2() = 0;
}
class ConcreteSpecialized : ConcreteBase, ISpecialized
{
public:
ConcreteSpecialized(){}
void method2() override { // some impl. }
}
The language allows it, it's clear and to the point, and you can use the override annotation which will help you should you ever refactor to another approach. I'd consider renaming ISpecialized though, if you're using I to specify an interface.
So other than the unnecessary ~IBase(){} there's nothing wrong at all with your approach.
If you want a virtual destructor then use
virtual ~IBase() = default;
i.e. don't define it explicitly.
Strictly from a software design point of view, I would not recommend on doing so.
There is no added benefit to ISpecialized inheriting from the ConcreteBase rather than the IBase class, since in both cases the interface will define the exact same set of methods. An interface is something you'd expect to be abstract.
If there is no direct relationship between the two interfaces, I would also recommend considering Mark's answer. In such case, it's better to separate them, thus allowing oneself to inherit a concrete implementation of the first one, while using only the definitions from the other.
I created Interfaces (abstract classes) that expends other Interfaces in C++ and I tried to implement them but errors occur when I compile.
Here are the errors:
main.cpp: In function 'int main()':
main.cpp:36:38: error: cannot allocate an object of abstract type 'Subclass'
Subclass * subObj = new Subclass();
^
Subclass.h:13:7: note: because the following virtual functions are pure within 'Subclass':
class Subclass : SubInterface {
^
SuperInterface.h:13:18: note: virtual void SuperInterface::doSomething()
virtual void doSomething()=0;
Here are my sources:
#include <iostream>
class SuperInterface {
public:
virtual void doSomething() = 0;
protected:
int someValue;
};
class SubInterface : public SuperInterface {
public:
virtual void doSomethingElseThatHasNothingToDoWithTheOtherMethod() = 0;
protected:
int anotherValue;
};
class Superclass : public SuperInterface {
public:
Superclass() {}
virtual ~Superclass() {}
void doSomething() {std::cout << "hello stackoverflow!";}
};
class Subclass : public SubInterface {
public:
Subclass() {}
virtual ~Subclass() {}
void doSomethingElseThatHasNothingToDoWithTheOtherMethod() {std::cout << "goodbye stackoverflow!";}
};
int main(void)
{
Superclass * superObj = new Superclass();
Subclass * subObj = new Subclass();
}
Here's what I want:
I want my implementation to be aware and so have the same behaviour as of already overriden methods (e.g subObj->doSomething() method works without the need to implement it again). Can anyone tell me what I should do to make that happen if it's even possible? Thanks.
No, you can't do what you want through simple inheritance. At no point does Subclass inherit, or provide, an implementation of doSomething(), so you can't call subObj->doSomething() as you desire. You must honour the interface contract of subInterface.
You could inherit Subclass from Superclass and Subinterface, and just implement doSomething() as a kind of proxy, Superclass::doSomething(). You still need an implementation but you don't have to 're-implement' it.
You're getting the error because you're trying to create an object of an abstract class.
Your Subclass is an abstract class because of this line void doSomethingElse()=0;.
If a class has one pure virtual function, it will be an abstract class. You can't create an object of an abstract class, you can only have a reference or a pointer to it.
To get rid of the error, the declaration of doSomethingElse in Subclass should be
void doSomethingElse();
Instead of void doSomethingElse()=0;
Also I don't see why you need two interfaces. You could derive Subclass from the SuperInterface, as it is basically just the same as SubInterface
To be honest, I am not entirely sure what your design wants to express, but there are at least two technical errors here:
1.) You use private inheritance in all cases, so you do not actually deal with "interfaces" at all. Public inheritance is achieved like this:
class SubInterface : public SuperInterface
2.) You use =0 for a function you apparently want to implement.
This will fix the compiler errors, but the design is still questionable. Considering the motivation you gave at the end of your question, I recommend composition rather than (public) inheritance. In C++, to share functionality is best expressed with composition. To put it very brief, encapsulate the commonly used functionality in a separate class and equip the other classes with an object of it.
class CommonFunctionality
{
//...
public:
void doSomething();
void doSomethingElse();
};
class SuperClass
{
//...
private:
CommonFunctionality m_functionality;
};
class SubClass : public SuperClass
{
//...
private:
CommonFunctionality m_functionality;
};
In fact, perhaps you don't even need to create a class for CommonFunctionality. Perhaps simple free-standing functions would do. Programmers with a Java background (and your code looks a bit like it) tend to put too stuff into classes than what is necessary in C++.
Your class 'Subclass' should override 2 pure virtual methods, so:
class Subclass : SubInterface {
public:
Subclass();
virtual ~Subclass();
void doSomethingElse() override;
void doSomething() override;
};
by not doing so or stating
void doSomethingElse()=0;
class Subclass becomes abstract too, which cannot be instantiated. You could havea look at :http://www.parashift.com/c++-faq-lite/pure-virtual-fns.html
Here's what I want: I want my implementation to be aware and so have
the same behaviour as of already overriden methods (e.g
subObj->doSomething() method works without the need to implement it
again). Can anyone tell me what I should do to make that happen if
it's even possible!!?? Thanks.
--> maybe declare the methods virtual not pure virtual
There are 2 problems, which are clearly stated by compiler:
Problem 1
SubInterface::doSomethingElse()() in Subclass is declared as pure virtual, disregarding that you trying to define it in source file (I'm pretty sure, that this is a copy-paste kind of errors).
class Subclass : SubInterface
{
public:
Subclass();
virtual ~Subclass();
void doSomethingElse() = 0; // still pure?
};
Solution is obvious:
class Subclass : SubInterface
{
public:
Subclass();
virtual ~Subclass();
virtual void doSomethingElse() override
{
}
};
(here using C++11 override specifier, so compiler will check correctness of overriding; it is not obligatory)
Problem 2
doSomething() is not even tried to be overriden, neither in SuperInterface, nor in Subclass, so it stays pure virtual. Although doSomething() is overriden in Superclass, Subclass has no idea about existance of Superclass.
Solution: override doSomething() either in SuperInterface, or in Subclass, or in any of children of Subclass (don't have them yet). For example, overriding in Subclass:
class Subclass : SubInterface
{
public:
Subclass();
virtual ~Subclass();
virtual void doSomething() override
{
}
virtual void doSomethingElse() override
{
}
};
Other issues:
You are inheriting without visibility specifier, i.e. privately. Use public inheritance until you really need something else:
class Derved : public Base {};
Your source files have .c extension, but containing C++ code. This can confuse some compilers if you do not state programming language explicitly via command line arguments. By convention, most programmers use .cpp extension, and most compilers treat such files as C++ source files.
So I'm trying to move some common code in a few classes that implement an interface* to an abstract base class. However, the abstract base class needs to know a little bit about how the derived classes want to do things in order to determine exactly what to do. However, I'm not entirely sure if I should implement this using a pure virtual function or a protected member variable.
I'll give a simple example describing what I'm trying to do.
The interface:
class SomeInterface
{
public:
void DoSomething() = 0;
// ...
};
The abstract base class I'm trying to implement using pure virtual function:
class AbstractBase : public SomeInterface
{
public:
virtual void DoSomething()
{
for (int i = 0; i < GetNumIterations(); i++)
{
// Call implementation in derived classes, for example
DoSomethingImpl();
}
}
protected:
virtual void DoSomethingImpl() = 0;
virtual int GetNumIterations() = 0;
};
A derived class:
class Derived1 : public AbstractBase
{
protected:
virtual void DoSomethingImpl()
{
// Do actual work.
}
virtual int GetNumIterations()
{
return 5;
}
};
Another derived class:
class Derived2 : public AbstractBase
{
protected:
virtual void DoSomethingImpl()
{
// Do actual work.
}
virtual int GetNumIterations()
{
return 1;
}
};
Or the other way would be using a protected variable:
class AbstractBase
{
public:
virtual void DoSomething()
{
for (int i = 0; i < numIterations; i++)
{
// Call implementation in derived classes, for example
DoSomethingImpl();
}
}
protected:
virtual void DoSomethingImpl() = 0;
int numIterations;
};
And the derived would be like:
class Derived1 : public AbstractBase
{
public:
Derived1()
: numIterations(5)
{
}
protected:
virtual void DoSomethingImpl()
{
// Do actual work.
}
};
Same thing for Derived2.
I know there's some overhead related to virtual methods (probably insignificant, but still), and that the protected variable might not be great for encapsulation, or that it could be forgotten and left uninitialized. So my question is basically, which of these is preferrable and why, or should I avoid this scenario altogether and try to handle it differently?
Note: my actual code is a bit more complicated. I havent't actually tested to see if this code works, so forgive me if it's incorrect.
*When I say interface, I mean a class containing only pure virtual functions.
In fact, what you are trying to do is very common. However, there is one more approach to implement this which explicitly defines the contract for derivatives of AbstractBase. Modifying your example it would look as follows:
class AbstractBase : public SomeInterface
{
public:
explicit AbstractBase(int numIterations) : numIterations(numIterations) {}
virtual void DoSomething()
{
for (int i = 0; i < numIterations; i++)
{
// Call implementation in derived classes, for example
DoSomethingImpl();
}
}
protected:
virtual void DoSomethingImpl() = 0;
// Can omit it, if not needed by derivatives
int GetNumIterations() { return numIterations; }
private:
int numIterations;
};
class Derived1 : public AbstractBase
{
public:
Derived1() : AbstractBase(5) {}
protected:
virtual void DoSomethingImpl()
{
// Do actual work.
}
};
class Derived2 : public AbstractBase
{
public:
Derived2() : AbstractBase(1) {}
protected:
virtual void DoSomethingImpl()
{
// Do actual work.
}
};
As you probably understand now, by contract I meant the constructor which now explicitly forces derivatives of AbstractBase to initialize it properly, so you would never mess it. The downside of this approach is that it introduces the additional field which would be possibly duplicated among numerous copies of say Derived1 in case if this 5 never changes in your situation. So if you care about memory footprint, then I'd not go for this one. However, if numIterations can be changed, then this approach is certainly the best of the 3 proposed ones. All you'd have to do is add proper setters for it into AbstractBase.
NOTE: My approach is sort of safer and better alternative to your 2nd one as it exactly addresses the issues you've mentioned, namely encapsulation hole (redundant exposure of implementation details) and contract weakness (when you might forget to initialize numIterations because you are not forced to). Therefore, you do not want to use your 2nd approach in your current situation.
The first approach that you've proposed is good too. Its advantage over mine is that it does not introduce any memory overhead. And as long as "number of iterations" does not change you don't need to introduce a field to store it. As a result, you have to override this GetNumIterations method in every derivative, but it's OK since this is a part of (strong) contract (pure virtual method) and you can never mess it too.
To conclude, as you can see, these 2 approaches are mutually exclusive, and it is very easy to decide which one to use by simply applying their pros and cons to your particular situation.
I'm trying to solve a problem where I have some classes in which I need to do some common work and then a bunch of problem specific work and when this is finished do some more processing common to all these classes.
I have a Base and Derived class that both have a function called Execute. When I call the derived version of this function, I'd like to be able to do some processing common to all my derived classes in the Base and then continue executing in my Derived::Execute and going back to Base::Execute to finish off with some common work.
Is this possible in C++ and how would one best go about doing that?
This is the idea, however it's probably not very workable like this:
class Base
{
public:
virtual void Execute();
};
Base::Execute() {
// do some pre work
Derived::Execute(); //Possible????
// do some more common work...
}
class Derived : public Base
{
public:
void Execute();
};
void Derived::Execute()
{
Base::Execute();
//Do some derived specific work...
}
int main()
{
Base * b = new Derived();
b.Execute(); //Call derived, to call into base and back into derived then back into base
}
Use a pure virtual function from base..
class Base
{
public:
void Execute();
private:
virtual void _exec() = 0;
};
Base::Execute() {
// do some common pre work
// do derived specific work
_exec();
// do some more common work...
}
class Derived : public Base
{
private:
void _exec() {
// do stuff
}
};
int main()
{
Base * b = new Derived();
b.Execute();
}
EDIT: changed the flow slightly after reading the question some more.. :) The above mechanism should match exactly what you require now -
i.e.
Base Common Stuff
Derived specific stuff
Base Common stuff again
This is called the NVI (Non-Virtual Interface, from Herb Sutter here) idiom in C++, and basically says that you should not have public virtual functions, but rather protected/private virtual functions. User code will have to call your public non-virtual function in the base class, and that will dispatch through to the protected/private virtual method.
From a design perspective the rationale is that a base class has two different interfaces, on one side the user interface, determined by the public subset of the class, and on the other end the extensibility interface or how the class can be extended. By using NVI you are decoupling both interfaces and allowing greater control in the base class.
class base {
virtual void _foo(); // interface to extensions
public:
void foo() { // interface to users
// do some ops
_foo();
}
};
Turn the problem from its head to its feet. What you actually want to have is a base class algorithm that derived classes can plug into:
class Base {
public:
void Execute()
{
// do something
execute();
// do some more things
}
private:
virtual void execute() = 0;
};
class Derived : public Base {
public:
// whatever
private:
virtual void execute()
{
//do some fancy stuff
}
};
Letting derived classes plug into base class algorithms is often called "template method" pattern (which has nothing to do with template. Having no public virtual functions in the base class interface is often called "non-virtual interface" pattern.
I'm sure google can find you a lot on those two.
Move that Base::Execute internally in two functions and then use RAII to implement that easily.
class Base{
protected:
void PreExecute(){
// stuff before Derived::Execute
}
void PostExecute(){
// stuff after Derived::Execute
}
public:
virtual void Execute() = 0;
};
struct ScopedBaseExecute{
typedef void(Base::*base_func)();
ScopedBaseExecute(Base* p)
: ptr_(p)
{ ptr_->PreExecute() }
~ScopedBaseExecute()
{ ptr_->PostExecute(); }
Base* ptr_;
};
class Derived : public Base{
public:
void Execute{
ScopedBaseExecute exec(this);
// do whatever you want...
}
};
In C++ an interface can be implemented by a class whose methods are pure virtual.
Such a class could be part of a library to describe what methods an object should implement to be able to work with other classes in the library:
class Lib::IFoo
{
public:
virtual void method() = 0;
};
:
class Lib::Bar
{
public:
void stuff( Lib::IFoo & );
};
Now I want to to use class Lib::Bar, so I have to implement the IFoo interface.
For my purposes I need a whole of related classes so I would like to work with a base class that guarantees common behavior using the NVI idiom:
class FooBase : public IFoo // implement interface IFoo
{
public:
void method(); // calls methodImpl;
private:
virtual void methodImpl();
};
The non-virtual interface (NVI) idiom ought to deny derived classes the possibility of overriding the common behavior implemented in FooBase::method(), but since IFoo made it virtual it seems that all derived classes have the opportunity to override the FooBase::method().
If I want to use the NVI idiom, what are my options other than the pImpl idiom already suggested (thanks space-c0wb0y).
I think you've got your NVI pattern around the wrong way:
http://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Non-Virtual_Interface
Not sure if that solves your issue though.
class IFoo
{
public:
void method() { methodImpl(); }
private:
virtual void methodImpl()=0;
};
class FooBase : public IFoo // implement interface IFoo
{
private:
virtual void methodImpl();
};
Here's an example of why you might do this using a reader that reads from XML and another from DB. Note that common structure is moved into the NVI readFromSource, while non-common behaviour is moved into the private virtual getRawDatum. This way logging and error checking is only needed in the one function.
class IReader
{
public:
// NVI
Datum readFromSource()
{
Datum datum = getRawDatum();
if( ! datum.isValid() ) throw ReaderError("Unable to get valid datum");
logger::log("Datum Read");
return datum;
}
private:
// Virtual Bits
Datum getRawDatum()=0;
};
class DBReader : public IReader
{
private:
Datum getRawDatum() { ... }
};
class XmlReader : public IReader
{
private:
Datum getRawDatum() { ... }
};
Commonly, the reason for using the NVI (sometimes also called "Template Method") is that derived classes should only change a part of the base class' behavior. So what you do is this:
class base {
public:
void f()
{
// do something derived classes shouldn't interfere with
vf();
// do something derived classes shouldn't interfere with
vg();
// do something derived classes shouldn't interfere with
vh();
// do something derived classes shouldn't interfere with
}
private:
virtual void vf(); // might be pure virtual, too
virtual void vg(); // might be pure virtual, too
virtual void vh(); // might be pure virtual, too
};
Derived classes can then plug into f() at the spots they are meant to and change aspects of f()'s behavior, without messing up its fundamental algorithm.
It may be confusing that once a method is declared as virtual in a base class, it automatically becomes virtual in all derived classes, even if the virtual keywords is not used there. So in your example, both methods of FooBase are virtual.
... to deny derived classes the
possibility of overriding the common
behavior implemented in
FooBase::method()...
If you can get rid of IFoo, and just start the hierarchy with FooBase with a non-virtual method, that would do it. But it looks like you want to allow direct children of IFoo to override method(), but to prevent children of FooBase to override it. I don't think that's possible.
You could use the pimpl-idiom to achieve this:
class IFoo
{
public:
IFoo( boost::shared_ptr< IFooImpl > pImpl )
: m_pImpl( pImpl )
{}
void method() { m_pImpl->method(); }
void otherMethod() { m_pImpl->otherMethod(); }
private:
boost::shared_ptr< IFooImpl > m_pImpl;
};
class IFooImpl
{
public:
void method();
virtual void otherMethod();
};
Now others can still subclass IFooImpl and pass it to IFoo, but they cannot override the behavior of method (they can override otherMethod). You can even make IFooImpl a direct subclass of IFoo and use enable_shared_from_this to initialize IFoo correctly. This is just the gist of the method. There are many ways to tweak this approach. For instance you can use the factory-pattern to make sure IFoos are created correctly.
Hope that helps.