Constructing thread executing a member function of a derived class - c++

I have two classes Base and Derived inheriting from each other. In Base I want to create a thread executing the member function Handle of the class (TThread is MT library of ROOT). I want to override this handle function in Derived, but my program always executes the function from the base class rather than the one from the derived class. How can I change it so that the overridden Handle is executed instead?
Here is the code:
#include "TThread.h"
#include <iostream>
using namespace std;
class Base
{
public:
Base()
{
thread = new TThread("BaseClass", (void(*)(void*))&Handle,(void*)this);
thread->Run();
}
private:
TThread *thread;
static void* Handle(void *arg)
{
cout<<"AAAA"<<endl;
}
};
class Derived : public Base
{
public:
Derived() : Base(){}
private:
static void* Handle(void *arg)
{
cout<<"BBBB"<<endl;
}
};
int main()
{
Derived *b = new Derived();
return 0;
}

You are trying to achieve polymorphism with on a non-virtual function.
The reference to Handle in your base class constructor gets resolved at compile time to always point to Base::Handle, no matter what the concrete type of the object at runtime will be. This can be fixed by changing Handle from a static to a virtual function.
The other problem is that you are trying to create the thread from the base class constructor. The derived object has not been fully constructed at this point, so you cannot polymorphically dispatch to Derived::Handle, even if you change it to a virtual function. A quick solution for this would be to move the thread construction to a Base::startThread() method and call that after the constructor has returned.

Make Handle virtual as #ComicSansMS says, and introduce a static member function to handle the virtual dispatch correctly:
#include "TThread.h"
#include <iostream>
using namespace std;
class Base
{
public:
Base() : thread() {}
~Base() { wait(); }
void wait() {
if (thread)
{
thread->Join();
delete thread;
thread = NULL;
}
}
void start()
{
thread = new TThread("BaseClass", &Dispatch, this);
thread->Run();
}
private:
TThread *thread;
virtual void Handle()
{
cout<<"AAAA"<<endl;
}
static void* Dispatch(void *arg)
{
static_cast<Base*>(arg)->Handle();
return NULL;
}
};
class Derived : public Base
{
public:
Derived() { start(); }
~Derived() { wait(); }
private:
virtual void Handle()
{
cout<<"BBBB"<<endl;
}
};
int main()
{
Derived b;
}

Related

Calling a protected function from instance inside a derived class

Currently, I am trying to solve the following situation.
I have a classB which contains some objects from a classA. Each classA has a function foo which needs to be executed. In the context of the program it makes since that classBinherits from classA since will need all of its functionality.
I would like to call the protected function from an instance of a base class.
I have the following test code:
#include <iostream>
class baseA
{
protected:
virtual bool foo()
{
std::cout <<"Base foo in action" << std::endl;
return true;
}
};
class classB
:public baseA
{
public:
baseA obj1_;
virtual bool foo()
{
std::cout <<"I am going to call base foo" << std::endl;
bool a = obj1_.foo(); // Can't be called
}
};
int main(int argc, char** argv)
{
classB obj;
obj.foo();
return 0;
}
Currently is does not work because the function foois protected in the current context.
I get the following error: error: ‘virtual bool baseA::foo()’ is protected within this contex
Is there a way to make it work while maintaining the protected specifier?
Best regards
Yes, there is a way. You can put a protected "forwarding" function into the base.
struct Base {
protected:
virtual void theFunc() = 0;
static void callTheFuncOn(Base *b) {
b->theFunc();
}
};
struct Derived: Base {
void test(Base *b) {
callTheFuncOn(b);
}
};

Thread creation on a derived class method results in error

I have an abstract class as follows:
class AbstractClass : public std::enable_shared_from_this<AbstractClass> {
public:
virtual ~AbstractClass() = default;
virtual bool Start() = 0;
virtual void Stop() = 0;
};
This is the derived class:
class DerivedClass : public AbstractClass {
public:
bool Start() override;
void Stop() override;
}
I am trying to create an object of derived class and a thread for the derived class method in another file:
// Create object
derivedClass_.reset(...);
//Start a thread for the derived class method
std::unique_ptr<boost::thread> derivedClassThread_;
derivedClassThread_.reset(new boost::thread(std::bind(&DerivedClass::Start,
derivedClass_)));
When I compile this, I get some weird errors:
error: no type named 'type' in 'class std::result_of<bool
(DerivedClass::* const&(const volatile
std::shared_ptr&))()>'
Could someone help me out?
Your code is not selfcontained, so we have to guess things. Here's what I think you would have/want:
Live On Coliru
#include <boost/thread.hpp>
#include <memory>
#include <iostream>
class AbstractClass : public std::enable_shared_from_this<AbstractClass> {
public:
virtual ~AbstractClass() = default;
virtual bool Start() = 0;
virtual void Stop() = 0;
};
class DerivedClass : public AbstractClass {
public:
bool Start() override {
std::cout << __PRETTY_FUNCTION__ << std::endl;
return true;
}
void Stop() override { }
};
int main()
{
// Create object
std::shared_ptr<AbstractClass> derivedClass_ =
std::make_shared<DerivedClass>();
// Start a thread for the derived class method
auto derivedClassThread_ = std::make_unique<boost::thread>(
[derivedClass_] { derivedClass_->Start(); });
if (derivedClassThread_ && derivedClassThread_->joinable())
derivedClassThread_->join();
derivedClassThread_ = std::make_unique<boost::thread>(
std::bind(&AbstractClass::Start, derivedClass_));
if (derivedClassThread_ && derivedClassThread_->joinable())
derivedClassThread_->join();
}
Which compiles without trouble.
Updated in response to the comment, showed that you can actually do it with std::bind just the same.
Prints:
virtual bool DerivedClass::Start()
virtual bool DerivedClass::Start()

Forbid child from invoking parent's abstract (or virtual) function

I have a parent class that invokes a callback that is abstract. The child class is meant to override this callback, but must never call it on its own from its code.
class Parent(){
public:
void Init(){ MyCallback(); }
protected:
virtual void MyCallback() = 0;//child must override, but child must never call it manually.
};
class Child : public Parent{
protected:
void MyCallback()override{ }
private:
void SomeCode{ MyCallback(); }//<---how to prevent this?
}
There are many callbacks such as these. I don't want the user to get lost and think that he should call any of them manually.
Is it possible to prevent these callbacks from being invoked by child class?
I don't think there is a way to enforce the rules you want at compile-time, but you can enforce them at runtime via assertion-failures, which is the next-best thing, since at least anyone who breaks the rule will learn the error of their ways the next time they run the program. Note that I've added a requirement that the subclass-overrides of MyCallback() must call up to the superclass-method exactly once, to prevent subclasses from gratuitously making additional calls to MyCallback() on themselves or their superclasses inside the callbacks-are-allowed context.
#include <stdio.h>
#include <stdlib.h>
class Parent
{
public:
Parent() : _okayToCallCount(0), _numParentClassCallsMade(0) {/* empty */}
protected:
virtual void MyCallback()
{
if (_okayToCallCount == 0) {printf("MyCallback() was called from an invalid context!\n"); abort();}
_numParentClassCallsMade++;
if (_numParentClassCallsMade > 1) {printf("Parent::MyCallback() was called more than once from the subclass's override-method!\n"); abort();}
}
private:
// This is the only place that MyCallback should EVER be called from!
void TheOnlyPlaceThatMyCallbackShouldEverBeCalledFrom()
{
_numParentClassCallsMade = 0;
_okayToCallCount++;
MyCallback();
_okayToCallCount--;
if (_numParentClassCallsMade < 1) {printf("Parent::MyCallback() was never called from the subclass's override-method!\n"); abort();}
}
int _okayToCallCount;
int _numParentClassCallsMade;
};
class Child : public Parent
{
public:
Child() {}
void SomeCode() { MyCallback(); }//<---how to prevent this?
protected:
virtual void MyCallback()
{
Parent::MyCallback(); // REQUIRED!
}
};
int main(int argc, char ** argv)
{
Child c;
c.SomeCode();
return 0;
}
Your Program had soo many mini Errors
class Parent(){ // These braces**()** don't come after a class's name
public:
void Init(){ MyCallback(); }
protected: // Because the datatype is protected, it can't be accessed properly (overrided) by **Main Function**
virtual void MyCallback() = 0;//child must override, but child must never call it manually.
};
class Child : public Parent{
protected:
void MyCallback()override{ }
private:
void SomeCode{ MyCallback(); }//<---how to prevent this? // You forgot the braces here **()**
} // You forgot the semi-colon **;**
Here I have fixed them for you:-
#include <iostream>
using namespace std;
class Parent {
public:
void Init(){ MyCallback(); }
//protected:
virtual void MyCallback() = 0;//child must override, but child must never call it manually.
};
class Child : public Parent{
protected:
void MyCallback()override{ cout <<"Child Class Function!"; }
private:
void SomeCode() { MyCallback(); }//<---how to prevent this?
};
int main()
{
Parent* ptr_base;
Child derived;
ptr_base = &derived;
ptr_base->MyCallback();
}

Requiring derived class to define a method

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;
}

use virtual method of base class C++ in child of child class

I've created a class named 'Device' which get inherited by multiple devices (for example, RFDevice, AccelleroDevice)
The Device class inherited a Thread class. This Threadclass includes a Pure virtual function named run. Is it possible to accesss this pure virtual function in RFDevice or AcelleroDevice.
So,
ThreadClass->DeviceClass->RFDeviceClass.
I've tried to add
' virtual void run(void) = 0' also in the device class but this wont work.
Greets,
Only if the virtual function is not private. If it is, then you cannot call it and are not supposed to, either:
class ThreadClass
{
public:
virtual ~ThreadClass() {}
private:
virtual void run() = 0;
};
class Device : public ThreadClass
{
};
class RFDevice : public Device
{
public:
void f()
{
run(); // compiler error
}
};
If it is protected or public, then it will work, provided there is an implementation of the function somewhere down the class hierarchy. But with the exception of the destructor, virtual functions should rarely be public or protected in C++:
class ThreadClass
{
public:
virtual ~ThreadClass() {}
protected:
virtual void run() = 0; // non-private virtual, strange
};
class Device : public ThreadClass
{
};
class RFDevice : public Device
{
protected:
virtual void run()
{
}
public:
void f()
{
run(); // works
}
};
Of course, this does not technically call the base function. And that's a good thing; you'd end up with a pure virtual function call otherwise, and your program would crash.
Perhaps what you need to do is to just implement the private virtual function. That would be the preferred class design:
class ThreadClass
{
public:
virtual ~ThreadClass() {}
void execute()
{
run();
}
private:
virtual void run() = 0;
};
class Device : public ThreadClass
{
};
class RFDevice : public Device
{
private:
virtual void run()
{
}
};
int main()
{
RFDevice d;
d.execute();
}
If you are not just maintaining a legacy code base, you should probably get rid of your thread class and use C++11 multi-threading.