Requiring derived class to define a method - c++

I am no doubt overlooking something basic but my implementation is obviously flawed.
I am trying to require a derived classes to implement a method being called in a base class.
class IClock
{
public:
virtual void OnTimeExpired() = 0;
}
class Clock : public IClock
{
... // ABC not implemented
}
class Application : public Clock
{
... // ABC not implemented
}
class DerivedApp : public Application
{
public:
virtual void OnTimeExpired() { ... }
}
I rarely use pure ABCs, so I thought by not defining the pure virtual method in Clock and Application, it would require all derivatives of Application to define the OnTimeExpired() method.
I discovered this will compile and link (MSVS-2017) and if DerivedApp does not implement the method, the Clock object will call an undefined method and crash.
Why does this compile without the pure virtual method being implemented?
How do I force derived Application classes to implement the OnTimeExpired() method?
EDIT: The crash was due to unrelated error - I apologize. Nevertheless the questions I ask are still applicable.
As requested here is a complete, buildable, minimal example:
IClock.h:
#pragma once
class IClock
{
public:
virtual void OnClockTime() = 0;
};
Clock.h:
#pragma once
#include "IClock.h"
class Clock : public IClock
{
public:
Clock();
virtual ~Clock();
void ClockUpdate();
virtual void OnClockTime();
private:
float elapsed_time;
};
Clock.cpp:
#include "Clock.h"
Clock::Clock()
: elapsed_time(0.0f)
{
}
Clock::~Clock()
{
}
void Clock::ClockUpdate()
{
elapsed_time += 0.0000001f; // small ticks for testing
if (elapsed_time >= 1.0f) {
OnClockTime();
elapsed_time -= 1.0f;
}
}
void Clock::OnClockTime()
{}
ApplicationBase.h
#pragma once
#include "Clock.h"
class ApplicationBase : public Clock
{
public:
ApplicationBase();
virtual ~ApplicationBase();
virtual void Init(){}
virtual void Run(){}
protected:
bool app_run;
};
ApplicationBase.cpp:
#include "ApplicationBase.h"
ApplicationBase::ApplicationBase()
: app_run(false)
{
}
ApplicationBase::~ApplicationBase()
{
}
DerivedApp.h:
#pragma once
#include "ApplicationBase.h"
class DerivedApp : public ApplicationBase
{
public:
DerivedApp();
virtual ~DerivedApp();
virtual void Init() {}
virtual void Run();
//virtual void OnClockTime();
};
DerivedApp.cpp:
#include "DerivedApp.h"
#include <iostream>
DerivedApp::DerivedApp()
{
}
DerivedApp::~DerivedApp()
{
}
void DerivedApp::Run()
{
app_run = true;
while (app_run) {
ClockUpdate();
}
}
//void DerivedApp::OnClockTime()
//{
// static int counts(0);
// std::cout << "Tick..." << std::endl;
// counts++;
// if (counts >= 10)
// app_run = false;
//}
main.cpp
#include "DerivedApp.h"
class App : public DerivedApp
{
public:
App(){}
~App(){}
};
int wmain(int argc, wchar_t * argv[])
{
App *app = new App();
app->Init();
app->Run();
delete app;
}
Thanks to those who requested a minimal working example, I built it and it works exactly as I had hoped. The complier will complain about no instantiation of the ABC in the App class. If I remove the comments from DerivedApp::OnClockTime() it compiles and runs the way I wish. Obviously my actual code is not following this model as I thought, so now I need to reexamine where I went wrong. Thanks.

There is no keyword in C++ that forces a class to override some method. However, by making OnTimeExpired() pure virtual you're making IClock an abstract class. Any classes deriving from IClock that do not implement OnTimeExpired() will automatically become an abstract class too, thus not allowing you to create objects of these classes. This means that your code as-is is completely legal unless you try to make objects of these classes

class AbstractBase {
public:
virtual void someFunc() = 0; // Purely Virtual
};
class AbstractDerived : public AbstractBase {
public:
void someOtherFunc();
// Still abstract because the following is not declared-defined
// void someFunc() override { ... }
};
class NonAbstractDerivedA : public AbstractBase { // Derived From Base
public:
void someFunc() override { /* do this class's implementation*/ }
};
class NonAbstractDerivedB : public AbstractDerived { // Derived From AbstractDerived
public:
void someFunc() override { /* do this class's implementation*/ }
};
uses:
#include "above"
int main() {
AbstractBase base; // compiler error
AbstractDerived derived; // compiler error
NonAbstractDerivedA derivedA; // should be okay
NonAbstractDerivedB derivedB; // should be okay
return 0;
}

Related

Creating List of abstract base class to fill with inherited objects

I want to create a List which is able to hold every Object I throw at it as long as they share the same ABSTRACT base class.
Here is an sample code of how I want to achieve this.
#include <iostream>
#include <memory>
#include <list>
class Observer
{
public:
virtual void update() = 0;
};
class RequestStateObserver
{
public:
void registerObserver(std::shared_ptr<Observer> o){
observerList.push_back(o);
}
private:
std::list<std::shared_ptr<Observer>> observerList;
};
class RestRequestCreator :Observer
{
void update() override;
};
void RestRequestCreator::update()
{
std::cout<<"RestRequestCreator::update()";
}
class dbHandler :Observer
{
void update() override;
};
void dbHandler::update() {
std::cout<<"dbHandler::update()";
}
int main()
{
RestRequestCreator rrc;
RequestStateObserver rso;
dbHandler dbhandler;
std::shared_ptr<RequestStateObserver> stateObserver;
std::shared_ptr<RestRequestCreator> rr_ptr = std::make_shared<RestRequestCreator>(rrc);
rso.registerObserver(rr_ptr);
rso.registerObserver(std::make_shared<Observer> (dbhandler));
}
o->registerObserver(std::make_shared<Observer> dbhandler)will tell me I can't create Observer since it's an abstract class which totally makes sense but
o->registerObserver(rr_ptr) will tell me it can't convert std::shared_ptr<Observer> to std::shared_ptr<RestRequestCreator>
I am at the moment not sure how to fix this problem or what exactly I should try next.
Would Templates help me? If I am correct they would just allow me to put as many objects of ONE child class into my List, if that's wrong please tell me and I will re-read about templates again.
The conversion fails because Observer is a private base of RestRequestCreator, and is inaccessible.
You'll need to use public inheritance for the compiler to implicitly convert from the derived class to the base:
class RestRequestCreator :public Observer
That fixes the immediate problem, but leaves the problems with make_shared<Observable> on the next line.
Also: should an observee co-own an observer? In general that would not be the case. Therefore, instead use regular pointers.
#include <list>
#include <iostream>
using std::cout;
class Observer
{
public:
virtual void update() = 0;
};
class ConcreteObserver : public Observer
{
public:
void update() override {
cout << "ConcreteObserver noticed update\n";}
};
class OtherKindConcreteObserver : public Observer
{
public:
void update() override {
cout << "OtherKindObserver noticed update\n";
}
};
class Subject
{
public:
void registerObserver( Observer* o) {
observerList.push_back( o);
}
void signalObservers() {
for ( auto observer : observerList)
observer->update();
}
private:
std::list<Observer*> observerList;
};
int main() {
ConcreteObserver observer1;
OtherKindConcreteObserver observer2;
Subject subject;
subject.registerObserver( &observer1);
subject.registerObserver( &observer2);
subject.signalObservers();
return 0;
}

Can I use inheritance this way somehow

Hi I would like use a virtual function of an inherited class without having to include it in the class prototype that would end up going in a header file. Is there any way to do this?
class Base {
public:
virtual void func () = 0;
};
class Derived : public Base {
public:
};
void Derived::func () {
return;
}
Is what I am thinking. In the case I am actually working with there are a large number of virtual function I may possibly use with any function and I don't want to bog down the class declaration with all the extra functions.
This is not possible with plain inheritance / virtual functions, but you could inject your implementation of func:
// header file
#include <functional>
class Base {
public:
Base(std::function<void()> func_impl)
: m_func_impl{ std::move(func_impl) }
{
}
void func() { m_func_impl(); }
private:
std::function<void()> m_func_impl;
};
class Derived : public Base {
public:
Derived();
};
// implementation file
static void Derived_func()
{
// your implementation of func
}
Derived::Derived()
: Base{ Derived_func }
{
}
You could accomplish the same by using the pimpl idiom. This avoids having a std::function for every method, but requires a secondary class hierachy:
// header file
#include <memory>
class Base {
public:
struct Impl
{
virtual ~Impl() {}
virtual void func() = 0;
};
Base(std::unique_ptr<Impl> impl)
: m_impl{ std::move(impl) }
{
}
void func() { m_impl->func(); }
private:
std::unique_ptr<Impl> m_impl;
};
class Derived : public Base {
public:
Derived();
};
// implementation file
class Derived_Impl : public Base::Impl
{
virtual void func() override
{
// your implementation of func
}
};
Derived::Derived()
: Base{ std::unique_ptr < Impl > {new Derived_Impl} }
{
}
Both solution have their drawbacks, most notably that the implementation is not within the derived class, so you have to think about how to adress scoping issues (e.g. accessing private members of the derived class in your implementations).

Virtual function call

Here is my hierarchic of classes.
I have declare following abstract interface class, which have just one function:
class IAuthenticator
{
public:
virtual void CreateJson() = 0;
};
After I have created on more class 'UIData' and inherits it from interface class, in this case:
class UIData : public IAuthenticator
{
protected:
UIData() : mWindowHandle(0)
{ /* Constructor do nothing. **/ }
private:
integer mWindowHandle;
public:
void CreateJson()
{
std::cout<<"UIData::CreateJson\n";
}
};
I have one more class which inherits from UIData
class AuthenticateIn : public UIData
{
private:
string mOrigin;
string mLogoURL;
string mUserID;
public:
void CreateJson()
{
std::cout<<"AuthenticateIn::CreateJson\n";
}
};
Question
In my main function I have write code like this.
int main()
{
AuthenticateIn* ai = new AuthenticateIn();
ai->CreateJson();
}
When I call CreateJson() function I see log "AuthenticateIn::CreateJson". I want to find a way to call CreateJson() and it will be called for all base classes.
I know that I can do that calling this->UIData::CreateJson() from AuthenticateIn class CreateJson function, but is there any other way to do that, some automatic way ? Thanks !!
is there any other way to do that, some automatic way
No, there isn't. You have to call the base class's implementation from the derived class. The compiler won't do this automatically since it doesn't know whether you actually want this.
You have to call the base class function in the derived class sort of like this:
void CreateJson() {
UIData::CreateJSon();
}
etc
No, there is no such way. If you want to call virtual function from base class you should do this directly.
You may not be able to force a call to a virtual base class, but you can use indirection to simulate the behaviour.
typedef int integer;
#include <iostream>
#include <string>
using std::string;
using std::cout;
class IAuthenticator
{
public:
virtual void CreateJson() = 0;
};
class UIData : public IAuthenticator
{
protected:
UIData() : mWindowHandle(0)
{ /* Constructor do nothing. **/ }
private:
integer mWindowHandle;
virtual void CreateJsonPrivate() = 0;
public:
void CreateJson()
{
CreateJsonPrivate();
std::cout<<"UIData::CreateJson\n";
}
};
class AuthenticateIn : public UIData
{
private:
string mOrigin;
string mLogoURL;
string mUserID;
virtual void CreateJsonPrivate()
{
std::cout<<"AuthenticateIn::CreateJson\n";
}
};
int main()
{
AuthenticateIn* ai = new AuthenticateIn();
ai->CreateJson();
}
Output:
AuthenticateIn::CreateJson
UIData::CreateJson

C++ abstract base class constructors/destructors - general correctness

I would like to have a C++ Interface that must be overridden (if this is possible) when inherited. So far, I have the following:
class ICommand{
public:
// Virtual constructor. Needs to take a name as parameter
//virtual ICommand(char*) =0;
// Virtual destructor, prevents memory leaks by forcing clean up on derived classes?
//virtual ~ICommand() =0;
virtual void CallMe() =0;
virtual void CallMe2() =0;
};
class MyCommand : public ICommand
{
public:
// Is this correct?
MyCommand(char* Name) { /* do stuff */ }
virtual void CallMe() {}
virtual void CallMe2() {}
};
I have purposely left how I think the constructor/destructor's should be implemented in ICommand. I know if I remove the comments, it will not compile. Please could someone:
Show me how to declare the constructor/destructor's in ICommand and how they are meant to be used in MyCommand
Have I set things up correctly in ICommand so that MyCommand must override CallMe and CallMe2.
C++ does not allow for virtual constructors. A simple implementation (without the virtual constructor) would look something like this:
class ICommand {
public:
virtual ~ICommand() = 0;
virtual void callMe() = 0;
virtual void callMe2() = 0;
};
ICommand::~ICommand() { } // all destructors must exist
Note that even a pure virtual destructor must be defined.
A concrete implementation would look exactly like your example:
class MyCommand : public ICommand {
public:
virtual void callMe() { }
virtual void callMe2() { }
};
You have a couple of options for the constructor. One option is to disable the default constructor for ICommand, so that subclasses will have to implement a constructor that calls your ICommand constructor:
#include <string>
class ICommand {
private:
const std::string name;
ICommand();
public:
ICommand(const std::string& name) : name(name) { }
virtual ~ICommand() = 0;
virtual void callMe() = 0;
virtual void callMe2() = 0;
};
ICommand::~ICommand() { } // all destructors must exist
A concrete implementation would now look something like this:
class MyCommand : public ICommand {
public:
MyCommand(const std::string& name) : ICommand(name) { }
virtual void callMe() { }
virtual void callMe2() { }
};
I know this one is old, but it is still my first hit on this issue. This is how I would do it.
Interface header foo.h:
#pragma once
#include <memory>
enum class Implementations {Simple, Fancy};
class Foo
{
public:
using Ptr = std::unique_ptr<Foo>;
virtual ~Foo() = default;
virtual void do_it() = 0;
};
Foo::Ptr create_foo(Implementations impl); // factory
Yes I know that "pragma once" is strictly speaking not standard, but it works for me.
Note that nothing is implemented here. There is no constructor: an abstract class can not be instantiated. You get a pointer to the interface through the factory. For the virtual function calls to work, they must be called through a pointer. The virtual destructor is defaulted because it doesn't have to do anything special except polymorphing to the implementation. The factory is a free function. No need to try to make it a static member or something like that. This is not java.
Interface foo.cpp:
#include "foo.h"
#include "foo_impl.h"
Foo::Ptr create_foo(Implementations impl)
{
switch (impl)
{
case Implementations::Simple:
return std::make_unique<Simple_foo>();
case Implementations::Fancy:
return std::make_unique<Fancy_foo>();
default:
return nullptr;
}
}
Here the factory is implemented. Notice that the factory has to know the implementation(s). That is why we don't implement it inline: if it was inline, the interface header would have to include the implementation header, and through it, knowledge of the implementation would "leak out" to the callsite.
The implementation header foo_impl.h:
#pragma once
#include "foo.h"
class Simple_foo : public Foo
{
void do_it() override;
};
class Fancy_foo : public Foo
{
void do_it() override;
};
Nothing special, just override the virtual functions of the interface. Because this exaple is simple, I put both implementations in the same files. In real applications that will be different.
The implementation foo_impl.cpp:
#include "foo_impl.h"
#include <iostream>
void Simple_foo::do_it()
{
std::cout << "simple foo\n";
}
void Fancy_foo::do_it()
{
std::cout << "fancy foo\n";
}
Just implement the functions.
The main.cpp:
#include "foo.h"
int main()
{
auto sf = create_foo(Implementations::Simple);
sf->do_it();
auto ff = create_foo(Implementations::Fancy);
ff->do_it();
return 0;
}
Through the enum we can select the implementation we want. The pointers are of type Foo::Ptr, an alias for std::unique_ptr<Foo>. The callsite has no knowledge of the implementation at all, only the interface.
The output will be as expected:
simple foo
fancy foo

is virtual inheritance from pure abstract classes (interfaces) necessary

Why is it that in the code below the compiler complains that PureAbstractBase is an ambiguous base class of MultiplyInheritedClass? I realize I have two copies of the PureAbstractBase in MultiplyInheritedClass and that FirstConreteClass and SecondConreteClass should be derived virtually because they're the middle row of the diamond (and that does indeed fix the problem with the code below). But even though I have two copies of the interface why is it that the code in MultiplyInheritedClass does not just override both and unambiguously pick the interface class defined in MultiplyInheritedClass?
#include <iostream>
using namespace std;
class PureAbstractBase {
public:
virtual void interface() = 0;
};
// I know that changing the following line to:
// class FirstConcreteClass : public virtual PureAbstractBase {
// fixes the problem with this hierarchy
class FirstConcreteClass : public PureAbstractBase {
public:
virtual void interface() { implementation(); }
private:
void implementation() { cout << "This is object FirstConcreteClass\n"; }
};
// I know that changing the following line to:
// class SecondConcreteClass : public virtual PureAbstractBase {
// fixes the problem with this hierarchy
class SecondConcreteClass : public PureAbstractBase {
public:
virtual void interface() { implementation(); }
private:
void implementation() { cout << "This is object SecondConcreteClass\n"; }
};
class MultiplyInheritedClass : public FirstConcreteClass,
public SecondConcreteClass {
public:
virtual void interface() { implementation(); }
private:
void implementation() { cout << "This is object MultiplyInheritedClass\n"; }
};
Further, why do I not have issues with the following hierarchy? Doesn't the ConcreteHandler class have three copies of the AbstractTaggingInterface in this case? So why doesn't it have the same issue as the example above?
#include <iostream>
using namespace std;
class AbstractTaggingInterface {
public:
virtual void taggingInterface() = 0;
};
class FirstAbstractHandler : public AbstractTaggingInterface {
public:
virtual void taggingInterface() { cout << "FirstAbstractHandler\n"; }
virtual void handleFirst() = 0;
};
class SecondAbstractHandler : public AbstractTaggingInterface {
public:
virtual void taggingInterface() { cout << "SecondAbstractHandler\n"; }
virtual void handleSecond() = 0;
};
class ThirdAbstractHandler : public AbstractTaggingInterface {
public:
virtual void taggingInterface() { cout << "ThridAbstractHandler\n"; }
virtual void handleThird() = 0;
};
class ConcreteHandler : public FirstAbstractHandler,
public SecondAbstractHandler,
public ThirdAbstractHandler {
public:
virtual void taggingInterface() = { cout << "ConcreteHandler\n"; }
virtual void handleFirst() {}
virtual void handleSecond() {}
virtual void handleThird() {}
};
I am trying to wrap my head around all of this because I had a conversation with a colleague recently where he claimed that if you were inheriting from pure virtual classes (interfaces) without any data members then virtual inheritance was not necessary. I think understanding why the former code example does not work and the latter does would go a long way to getting this straight in my head (and clear up what exactly he meant by his comment). Thanks in advance.
You need virtual inheritance to overcome the diamond-ambiguity:
class FirstConcreteClass : public virtual PureAbstractBase { ... };
class SecondConcreteClass : public virtual PureAbstractBase { ... };
Long-winded explanation: Suppose you have this:
// *** Example with errrors! *** //
struct A { virtual int foo(); };
struct B1 : public A { virtual int foo(); };
struct B2 : public A { virtual int foo(); };
struct C: public B1, public B2 { /* ... */ }; // ambiguous base class A!
int main() {
A * px = new C; // error, ambiguous base!
px->foo(); // error, ambiguous override!
}
The inheritance of the virtual function foo is ambiguous because it comes in three ways: from B1, from B2 and from A. The inheritance diagram forms a "diamond":
/-> B1 >-\
A-> ->C
\-> B2 >-/
By making the inheritance virtual, struct B1 : public virtual A; etc., you allow any baseclass of C* to call the correct member:
struct A { virtual int foo(); };
struct B1 : public virtual A { virtual int foo(); };
struct B2 : public virtual A { virtual int foo(); };
struct C: public B1, public B2 { virtual int foo(); };
We must also define C::foo() for this to make sense, as otherwise C would not have a well-defined member foo.
Some more details: Suppose we now have a properly virtually-inheriting class C as above. We can access all the various virtual members as desired:
int main() {
A * pa = new C;
pa->foo(); // the most derived one
pa->A::foo(); // the original A's foo
B1 * pb1 = new C;
pb1->foo(); // the most derived one
pb1->A::foo(); // A's foo
pb1->B1::foo(); // B1's foo
C * pc = new C;
pc->foo(); // the most derived one
pc->A::foo(); // A's foo
pc->B1::foo(); // B1's foo
pc->B2::foo(); // B2's foo
pc->C::foo(); // C's foo, same as "pc->foo()"
}
Update: As David says in the comment, the important point here is that the intermediate classes B1 and B2 inherit virtually so that further classes (in this case C) can inherit from them while simultaneously keeping the inheritance from A unambiguous. Sorry for the initial mistake and thanks for the correction!
Your first example fails because the compiler cannot disambiguate between the three implementations of implementation(). You are overriding that method in MultiplyInheritedClass, which actually overrides both FirstConcreteClass::implementation and SecondConcreteClass::implementation (once virtual, always virtual). However, both virtual calls still exist in the interface of MultiplyInheritedClass, which makes the call ambiguous at the call site.
The reason that your example works without virtual inheritance is that there is no conflicting implementation of the common base class. Put another way:
class Base
{
public:
void DoSomething() {
std::cout << "TADA!";
}
}
class One : public Base
{
//...
}
class Two : public Base
{
//...
}
class Mixed : public One, public Two
{
//...
}
int main()
{
Mixed abc;
abc.DoSomething(); //Fails because the compiler doesn't know whether to call
// One::DoSomething or Two::DoSomething, because they both
// have implementations.
//In response to comment:
abc.One::DoSomething(); //Succeeds! You removed the ambiguity.
}
Because your example has all pure virtual functions, there's no multiple implementations which the compiler needs to disambiguate. Therefore, only one implementation exists, and the call is unambiguous.
I tried both of the question codes and they worked fine when instantiating an object of the multi-inherited class. It didn't work only with polymorphism, like this for example:
PureAbstractBase* F;
F = new MultiplyInheritedClass();
And the reason is clear: it doesn't know to which copy of the Abstract base class it should be linked (sorry for bad expressions, I understand the idea but can't express it). And since inherting virtaully makes only one copy exist in the derived class, then it's fine.
Also the code of Billy ONeal is not clear at all, what should we place instead of the comments?
If we place:
public:
void DoSomething()
{ std::cout << "TADA!"; }
it works fine, because of no virtuality.
I work on Visual Studio 2008.
Why not do it like this (suggested in Benjamin Supnik's blog entry):
#include <iostream>
class PureAbstractBase {
public:
virtual void interface() = 0;
};
class FirstConcreteClass : public PureAbstractBase {
public:
virtual void interface() { implementation(); }
private:
void implementation() { std::cout << "Fisrt" << std::endl; }
};
class SecondConcreteClass : public PureAbstractBase {
public:
virtual void interface() { implementation(); }
private:
void implementation() { std::cout << "Second" << std::endl; }
};
class MultiplyInheritedClass : public FirstConcreteClass,
public SecondConcreteClass
{
public:
virtual void interface() { implementation(); }
private:
void implementation() { std::cout << "Multiple" << std::endl; }
};
int main() {
MultiplyInheritedClass mic;
mic.interface();
FirstConcreteClass *fc = &mic; //disambiguate to FirstConcreteClass
PureAbstractBase *pab1 = fc;
pab1->interface();
SecondConcreteClass *sc = &mic; //disambiguate to SecondConcreteClass
PureAbstractBase *pab2 = sc;
pab2->interface();
}
which gives:
Multiple
Multiple
Multiple
This way:
no virtual bases are involved (do you really need them?)
you can call the overriden function via a an instance of the MultiplyInheritedClass
ambiguity is removed by a two-stage conversion