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

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

Related

cpp/arduino: classes call inherited virtual method [duplicate]

This question already has answers here:
Can I call a base class's virtual function if I'm overriding it?
(8 answers)
Closed last year.
I'm struggling to find the right answer on below question on the internet.
I'm not a native C++ programmer and have more knowledge of OOP programming in PHP, Pascal, and JavaScript, but i can manage.
I want to create a class hierarchy to handle some tasks like displaying content on a LCD screen.
It looks like the following classes:
class base {
public:
base() { };
virtual void display() { // Need to be called first from all child objects };
virtual bool keyPress(int state) { //Need to be called first from all child objects };
};
class child : public base {
public:
child():base() {};
virtual void display() {
>> call base->display()
// do some stuff
};
virtual bool keyPress(int state) {
>> call base->keyPress(state)
// check some stuff
};
};
Most program language that i know of has some 'parent::' solution to call the inherited virtual method but i cant find anything comparable for C++.
an option that i going to use for now is:
class base {
protected:
virtual void _display() =0;
virtual bool _keyPress(int state) =0;
public:
base() { };
void display() {
// do basic stuff
_display();
};
bool keyPress(int state) {
if (!_keyPress(state)) {
// do basic stuff.
};
};
class child : public base {
protected:
virtual void _display() {
// do some stuff
};
virtual bool _keyPress(int state) {
// check some stuff
};
public:
child():base() {};
};
I do not like this method but it will work.
The right syntax is base::display():
class base {
public:
base() { };
virtual void display() { /* Need to be called first from all child objects*/ };
virtual bool keyPress(int state) { /*Need to be called first from all child objects*/ return 42; };
};
class child : public base {
public:
child():base() {};
virtual void display() {
base::display();
// do some stuff
};
virtual bool keyPress(int state) {
return base::keyPress(state);
// check some stuff
};
};
However, if it is the same in all child classes you better let base call its methods like you do it in your second code. It is not clear why you "do not like this method". It works, does what you want, and avoids lots of duplicate code and decreases chances for mistakes in the derived classes. Just note that the virtual methods need not be protected, because the derived classes are not supposed to call them directly, you can make them private: https://godbolt.org/z/1qjooKq85 (perhaps that is what you didn't like?).

How can I access these functions on the derived class? [duplicate]

How do I call the parent function from a derived class using C++? For example, I have a class called parent, and a class called child which is derived from parent. Within
each class there is a print function. In the definition of the child's print function I would like to make a call to the parents print function. How would I go about doing this?
I'll take the risk of stating the obvious: You call the function, if it's defined in the base class it's automatically available in the derived class (unless it's private).
If there is a function with the same signature in the derived class you can disambiguate it by adding the base class's name followed by two colons base_class::foo(...). You should note that unlike Java and C#, C++ does not have a keyword for "the base class" (super or base) since C++ supports multiple inheritance which may lead to ambiguity.
class left {
public:
void foo();
};
class right {
public:
void foo();
};
class bottom : public left, public right {
public:
void foo()
{
//base::foo();// ambiguous
left::foo();
right::foo();
// and when foo() is not called for 'this':
bottom b;
b.left::foo(); // calls b.foo() from 'left'
b.right::foo(); // call b.foo() from 'right'
}
};
Incidentally, you can't derive directly from the same class twice since there will be no way to refer to one of the base classes over the other.
class bottom : public left, public left { // Illegal
};
Given a parent class named Parent and a child class named Child, you can do something like this:
class Parent {
public:
virtual void print(int x);
};
class Child : public Parent {
void print(int x) override;
};
void Parent::print(int x) {
// some default behavior
}
void Child::print(int x) {
// use Parent's print method; implicitly passes 'this' to Parent::print
Parent::print(x);
}
Note that Parent is the class's actual name and not a keyword.
If your base class is called Base, and your function is called FooBar() you can call it directly using Base::FooBar()
void Base::FooBar()
{
printf("in Base\n");
}
void ChildOfBase::FooBar()
{
Base::FooBar();
}
In MSVC there is a Microsoft specific keyword for that: __super
MSDN:
Allows you to explicitly state that you are calling a base-class implementation for a function that you are overriding.
// deriv_super.cpp
// compile with: /c
struct B1 {
void mf(int) {}
};
struct B2 {
void mf(short) {}
void mf(char) {}
};
struct D : B1, B2 {
void mf(short) {
__super::mf(1); // Calls B1::mf(int)
__super::mf('s'); // Calls B2::mf(char)
}
};
If access modifier of base class member function is protected OR public, you can do call member function of base class from derived class.
Call to the base class non-virtual and virtual member function from derived member function can be made.
Please refer the program.
#include<iostream>
using namespace std;
class Parent
{
protected:
virtual void fun(int i)
{
cout<<"Parent::fun functionality write here"<<endl;
}
void fun1(int i)
{
cout<<"Parent::fun1 functionality write here"<<endl;
}
void fun2()
{
cout<<"Parent::fun3 functionality write here"<<endl;
}
};
class Child:public Parent
{
public:
virtual void fun(int i)
{
cout<<"Child::fun partial functionality write here"<<endl;
Parent::fun(++i);
Parent::fun2();
}
void fun1(int i)
{
cout<<"Child::fun1 partial functionality write here"<<endl;
Parent::fun1(++i);
}
};
int main()
{
Child d1;
d1.fun(1);
d1.fun1(2);
return 0;
}
Output:
$ g++ base_function_call_from_derived.cpp
$ ./a.out
Child::fun partial functionality write here
Parent::fun functionality write here
Parent::fun3 functionality write here
Child::fun1 partial functionality write here
Parent::fun1 functionality write here
Call the parent method with the parent scope resolution operator.
Parent::method()
class Primate {
public:
void whatAmI(){
cout << "I am of Primate order";
}
};
class Human : public Primate{
public:
void whatAmI(){
cout << "I am of Human species";
}
void whatIsMyOrder(){
Primate::whatAmI(); // <-- SCOPE RESOLUTION OPERATOR
}
};
struct a{
int x;
struct son{
a* _parent;
void test(){
_parent->x=1; //success
}
}_son;
}_a;
int main(){
_a._son._parent=&_a;
_a._son.test();
}
Reference example.

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

Can I call method in each base recursively without manually typing base::Method()?

The content
The question
Example
Why do I need it
Hi.
The question
I am facing a problem. I have a class A that has a base B (is polymorphic). In B class is method Print(), wich is virtual. In A class is also Print(). virtual.
Lets say I am given an A type object (or pointer), stored in B variable
B * object = new A();
And by calling
object->Print();
It calls the method in A class, but I also want it to call method in B class.
Technically
I want to call the method for each child until i reach class that has no child
This can be done as follows:
Example
class A
{
public:
virtual void Print() const override
{
cout << "A" << endl;
}
};
class B : public A
{
public:
virtual void Print() const override
{
cout << "B" << endl;
A::Print(); // i do not want to call it here...
}
};
The problem is that I do want not to be forced to call the
A::Print();
Why
Yes, you might be asking, what is the deal...
I have very long inheritance chain. (lets say that there are like 15 - 20 classes in the inheritance chain).
In a game, each one does some little thing.
Lets say
class GameObject
{
public:
virtual void Update() const
{
//updates position, recounts it towards screen
}
};
class Character : public GameObject
{
public:
virtual void Update() const override
{
// Updates lives, movement
}
};
class Warrior : public Character
{
public:
virtual void Update() const override
{
// Updates armor, specific stuff
}
};
Now this example is very simplified. Problem is, that if i forget to add a call base::Update() Then I am worndering why does it not work. Looking for such a misstake is hard. I mean, if there any way around it?
Thank you very much indeed for any responses.
Have a nice day
If indeed every class must call the base function, one way to ensure the functionality is enforced is to use the template pattern.
class GameObject
{
public:
void Updater()
{
Update(); // this is a virtual call
GameObject::Update(); // now call base
}
virtual void Update() const
{
}
};
class Character : public GameObject
{
public:
virtual void Update() const override
{
// Updates lives, movement
}
};
class Warrior : public Character
{
public:
virtual void Update() const override
{
// Updates armor, specific stuff
}
};
class Character : public GameObject
{
public:
virtual void Update() const override
{
// Updates lives, movement
}
};
class Warrior : public Character
{
public:
virtual void Update() const override
{
// Updates armor, specific stuff
}
};
Then always call YourObject::Updater(); instead of YourObject::Update(). The Updater function will call your object's Update function, and then return and call the base class Update.
There was once a proposal to get all the bases of a given type (N2965) which gcc actually implemented in <tr2/type_traits>. So, if portability is not a concern and you happen to be using gcc, you can write a catch-all like so:
struct A {
virtual ~A() = default;
virtual void print() { print_all(*this); }
void print_one() { std::cout << "A\n"; }
protected:
template <class T>
void print_all(T& object) {
object.print_one();
print_all(object, typename std::tr2::bases<T>::type{});
}
template <class T, class... Bases>
void print_all(T& object, std::tr2::__reflection_typelist<Bases...> ) {
using swallow = int[];
(void)swallow{0,
(static_cast<Bases&>(object).print_one(), 0)...
};
}
};
This splits up print(), which prints everything, and print_one() which just prints the one specific type. You just have your print() call print_all() with itself:
struct B : A {
void print() override { print_all(*this); }
void print_one() { std::cout << "B\n"; }
};
struct C : B {
void print() override { print_all(*this); }
void print_one() { std::cout << "C\n"; }
};
Otherwise, you'll have to wait for one of the reflection proposals to get adopted.

Constructing thread executing a member function of a derived class

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