How to call overriden methods in all derived classes [duplicate] - c++

This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
How to force child same virtual function call its parent virtual function first
I have a class hierarchy where each derived class overrides a given virtual function and starts its implementation by calling the one in its parent class. The goal is to have each of the derived implementation to be executed, but I do not like the way I do it.
For example, I have this class:
class base
{
public:
void do_stuff() { do_something(); }
virtual void do_something() { }
};
Then I derive this class on several levels:
class derived_10:
public derived_9 // which inherit from derived_8 and so on until derived_0
// which inherit from base
{
public:
virtual void do_something()
{
// this will also call derived_8::do_something() and so on
// until base::do_something()
derived_9::do_something();
// then, some stuff
}
};
I'm looking for a solution that will make sure that all derived_x::do_something() will be called in sequence when base::do_stuff() is called, without having to expect the derived classes to do this themselves. Do you have an idea of the best way to get this behavior ?

I've already asked a very similar question before: Calling overriden class methods as a chain in C++
The answer I've accepted pointed at your own solution. I can give you an idea about an alternative though. Constructors and destructors already have this behavior in C++, you might want to consider restructuring your code, so that the work is done during the construction or the destruction of an object that belongs to a class in a hierarchy. I'm not sure you'll be able to make this worth the effort though. On the other hand, you never know what you can get out of some template metaprogramming + some preprocessor magic.

Related

C++ Call child function from parent [duplicate]

This question already has answers here:
call to pure virtual function from base class constructor
(8 answers)
Calling virtual functions inside constructors
(15 answers)
Closed 1 year ago.
I am trying to call an overriden function from the parent, and found out that it just crashes.
This is quite hard to describe, so here the minimal reproducible code:
#include <iostream>
class A
{
public:
A()
{
init1();
}
void init1()
{
printf("1");
init2();
printf("2");
}
virtual void init2() = 0;
};
class B : public A
{
public:
B()
: A()
{}
void init2() override
{
printf("hello");
}
};
int main()
{
B b;
return 0;
}
On MSVC 2019 it crashes, on http://cpp.sh/ it outputs "1" and then main() returns 0, but we never see "hello" or "2".
Why does it crash? What happens from a low level point of view? Is A trying to call its own init2()?
Is there a way of doing it, so I don't have to, in every derived class, add init2() in its constructor?
You can't call a derived class's overriden methods from within a base class constructor (or destructor). The derived class portion of the object doesn't exist yet.
So, to answer your questions:
yes A::A() is trying to call A::init2(), not B::init2(), and thus crashes from calling a pure virtual method.
There are ways (like via CRTP) for a base class constructor to call a derived class method, but doing so has limitations to it (ie, not being able to access any derived class data members since they still don't exist yet, only base class data members can be accessed). In your example, B::init2() doesn't access anyB data members, so it is possible for A::A() to call B::init2(), but in general you really need to wait for B to begin/finish constructing itself before you can safely call B::init2().

Should one declare functions virtual at all levels of inheritance or only at the ancestor level? [duplicate]

This question already has answers here:
C++ Style: Prefixing virtual keyword to overridden methods
(6 answers)
Closed 6 years ago.
Should one mark explicitly as virtual all overrides in descendant classes at any level?
class Base {
// ...
protected:
virtual void to_be_derived() const; // First level to introduce this virtual function
};
class LevelOne : public Base {
// ...
protected:
// virtual??
void to_be_derived() const;
};
class LevelTwo : public levelOne {
// ...
protected:
// virtual??
void to_be_derived() const;
};
I didn't see the Prefixing virtual keyword to overridden methods which answers my question. In particular, one of the answers there was updated to reflect current usage with respect to c++11, especially the override keyword that I didn't know about!
EDIT: I'd rather accept another answer from the linked question for post-c++11 code.
Nowadays, it's better to mark them as override. It tells the reader the function is virtual, and is also a fail-safe mechanism (in case you get the signature wrong).
I'd only use virtual if that was consistent with already existing code.
class LevelOne : public Base {
protected:
void to_be_derived() const override;
// |
// clearly virtual, certain it's the same signature as the base class
};
It's better to mark them as virtual and override. Virtual will prevent you from calling wrong function for delivered object. And override will prevent you from mistakes in signature and will make code more readable.
As Scott Meyers wrote in effective c++ book, you should't redefine in delevired classes non virtual functions.
Base Class Virtual would force the inheriting class ie LevelOne to override it.
Unless you need LevelTwo to override LevelOne's implementation , you do not need to mark it as virtual.
In general, unless the derived class has to override it, no need of using virtual

C++ standard way to create "Abstract Class" (Pure Virtual Class) [duplicate]

This question already has answers here:
C++ abstract class without pure virtual functions?
(3 answers)
Closed 7 years ago.
I will start with what's most of us already know:
If I want my class to be abstract, I must define at least one of its methods as "pure virtual", for example, here, the method someFunction() is defined as "pure virtual", as it is defined with the virtual keyword and it is assigned with 0:
class SomeClass {
virtual void someFunction() = 0;
};
My question is, when I want an "abstract class", i.e. a class which cannot be instantiated (like "pure virtual" class), but I want to implement all its methods. Is there any standard way to do it?
My current workaround is ugly - I just define another dummy pure virtual method:
class UglyWorkaround {
public:
virtual void doAction1();
virtual void doAction2();
// My ugly workaround for making the class abstract - defining a dummy method
virtual void thisIsADummyMethod() = 0;
};
This is very bad, as any deriving non-abstract class will have to implement it
Is there a more standard/popular way to define and implement such a class?
I want to clarify - I don't want another ugly workaround - I ask whether there is any standard way that is commonly used. The objective is to make the code readable for other programmers, so they immediately understand that the class is abstract
Define the constructor protected

Is there a way to cast an abstract object to its child? [duplicate]

This question already has answers here:
C++ cast to derived class
(4 answers)
Closed 7 years ago.
Let's imagine a situation where I have an abstract class named 'Base' with a virtual pure method named foo(), and 2 children (Inherited1 and Inherited2) that both implement this method in their own way. Now let's say that one of these children (Inherited1) needs another method called bar() that would make no sense to implement in Inherited2.
In my main, i Have
Base * randomObject = new Inherited1();
I can't access this method using
random->bar();
What should I do. Like I said, it would make no sense to implement it in inherited2, so I can't simply put another virtual method in Base, or should I?
If you had a variable
Base* randomObject = new Inherited1();
You could cast it down to the base class
Inherited1* foo = static_cast<Inherited1*>(randomObject);
foo->bar();
But you have to be sure that the pointer is indeed of that derived class otherwise static_cast isn't safe. There are a number of ways to do this, such as storing an enum in the derived classes that you can check via a virtual getter, or checking if the result of a dynamic_cast is nullptr, but that is slower.

Override vs Overwrite [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
C++ Overriding… overwriting?
What's the difference between override and overwrite? I've heard them used interchangeably but I suspect that's incorrect.
You can only overwrite what's been written and where it's been written, while you can override things elsewhere (for instance you can override members of base class in derived classes).
override is a C++11 keyword used to override base virtual method:
class A
{
virtual f(int) {}
};
class B
{
virtual f(int) override {} // override A::f(int)
};
This lets you make sure that A::F(int) gets overriden, meaning you are not creating new virtual function.
Of course this code won't compile if the function signature was different.
overwrite is not C++ keyword and it basically means to overwrite some file or text with new one.
The keyword override has been introduced because some times a programmer doesn't know whether he is overriding or whether he is creating a new virtual method with a different signature.
Using that keyword you either get an error or override virtual method.