Bringing non-virtual interfaces and multi-level inheritance together - c++

The Non-virtual Interface idiome (NVI) is pretty self explanatory: You don't write public virtual functions, but public functions that call a private virtual implementation function, like so:
class Object{
virtual void v_load();
public:
void load(){ v_load(); }
}
This enables you, the base class author, to check and enforce pre- and post-conditions or apply other functions so the author of deriving classes can't forget about them.
Now when you are the deriving author, you may want to write a base class yourself - let's call it Pawn - that extends on the functionality of load() and therefore has to override v_load(). But now you are facing a problem:
When you override v_load(), other clients that want to derive from your class, will always overwrite that behaviour, and they can not call Pawn::v_load() because it is a private function, neither can they call Pawn::load() because it is defined as { v_load; } in Object which will of course lead to an infinite loop. Additionally, requiring them to do so could lead to mistakes when they forget that call. If I would want them to enable that, I would have to specify the acces to v_load() as protected in Object, which seems like an ugly solution as it would weaken the encapsulation of Object greatly.
You could of course still override v_load() to call a new function v_pawnLoad(), which is then overridden by clients, but that seems very error-prone as a lot of clients will probably overload the wrong function.
So, how can I design Pawn in such a way that clients can still override v_load() while keeping the ability to check pre-conditions or call other functions and (if possible) not enabling, let alone requiring clients of Object or Pawn to call the base v_load() implementation?

If your intention is to allow people to "extend" as opposed to "replace" load's behaviour, then put the code you currently have in v_load in load then call an empty v_load in the end.
Or you could just make v_load protected if you want to let people choose between "replacing" or "extending".
If you just want to allow them to replace the behaviour, your code is fine as it is.
As a bonus, in all these 3 variants you can change "allow" with "force" by making your v_load a pure virtual if you have no default behaviour.
If you wish to limit the override to your Pawn child class, add the final keyword to v_load in Pawn and use another virtual function to allow children of Pawn to customise its behaviour.

How about mixin' in some CRTP?
#include <iostream>
class BaseObject
{
private:
virtual void v_load() = 0;
public:
void load() { v_load(); }
};
template<typename Derived>
class Object : public BaseObject
{
private:
virtual void v_load() { static_cast<Derived&>(*this).load(); }
};
class Pawn : public Object<Pawn>
{
public:
void load() { std::cout << "Pawn::load()" << std::endl; }
};
class BlackPawn : public Pawn
{
private:
virtual void v_load() {
std::cout << "BlackPawn::v_load()" << std::endl;
std::cout << "- "; Pawn::load();
}
public:
void load() {
std::cout << "BlackPawn::load()" << std::endl;
std::cout << "- "; Pawn::load();
}
};
class BigBlackPawn : public BlackPawn
{
private:
virtual void v_load() {
std::cout << "BigBlackPawn::v_load()" << std::endl;
std::cout << "- "; BlackPawn::load();
}
public:
void load() {
std::cout << "BigBlackPawn::load()" << std::endl;
std::cout << "- "; BlackPawn::load();
}
};
template<typename T>
void load(T& x)
{
x.load();
}
void vload(BaseObject& x)
{
x.load();
}
int main()
{
Pawn p;
BlackPawn bp;
BigBlackPawn bbp;
load(p);
load(bp);
load(bbp);
std::cout << std::endl;
vload(p);
vload(bp);
vload(bbp);
}
Output on ideone.

Related

Inheritance and templates instanciations with pointers to simulate "virtual data"

I have a hierarchy of classes:
class Base
{
public:
Base():a{5}{}
virtual ~Base(){};
int a;
};
class Derived : public Base
{
public:
Derived():b{10}{}
int b;
};
I then have a class template that operates on whatever type it is instanciated with:
template<typename T>
class DoStuff
{
public:
DoStuff():val{}{}
virtual ~DoStuff(){};
virtual void printDoStuff() = 0;
T getVal(){return val;};
private:
T val;
};
class DoStuffWithInt : public DoStuff<int>
{
public:
virtual void printDoStuff() override {cout << "val = " << getVal() << endl;}
};
class DoStuffWithBase : public DoStuff<Base>
{
public:
virtual void printDoStuff() {cout << "a = " << getVal().a << endl;}
};
Now I would like to have a hierarchy of class like this:
class DoStuffWithBase : public DoStuff<Base>
{
public:
virtual void printDoStuff() {printVal(); cout << "a = " << getVal().a << endl;}
};
// Wrong and will not compile, trying to make a point
class DoStuffWithDerived : public DoStuffWithBase<Derived>
{
public:
void printDoStuff() override {DoStuffWithBase::printDoStuff(); cout << "b = " << getVal().b << endl;}
};
Basically I would like to have DoStuffWithBase that operates on a base be extended so that I can reuse its functions, but the extended class DoStuffWithDerived should operate on a Derived type.
I managed to get something working by templating DoStuffWithBase with a pointer to Base and extending it:
template <class T>
static void deleteIfPointer(const T& t)
{
std::cout << "not pointer" << std::endl;
}
template <class T>
static void deleteIfPointer(T* t)
// ^
{
std::cout << "is pointer" << std::endl;
delete t;
}
template<typename T>
class DoStuff
{
public:
DoStuff():val{}{}
DoStuff(const T& value):val{value}{};
virtual ~DoStuff(){deleteIfPointer(val);}
virtual void printDoStuff() = 0;
T getVal(){return val;};
private:
T val;
};
class DoStuffWithBase : public DoStuff<Base*>
{
public:
// New base
DoStuffWithBase(): DoStuff(new Base()){}
DoStuffWithBase(Base* b) : DoStuff(b){}
virtual void printDoStuff() {printVal(); cout << "a = " << getVal()->a << endl;}
};
class DoStuffWithDerived : public DoStuffWithBase
{
public:
// New derived
DoStuffWithDerived(): DoStuffWithBase(new Derived()){}
void printDoStuff() override {DoStuffWithBase::printDoStuff(); cout << "b = " << static_cast<Derived*>(getVal())->b << endl;}
};
It works but there are several things I don't like:
The code is a lot more complicated, when 99% of the time, I won't need to extend a DoStuffWithX class, I will just use DoStuffWithInt, DoStuffWithClass, DoStuffWithAnotherClass etc... Here I had to add several constructors, a special case destructor and so on.
I have to use pointers and manage them (static_cast when needed, deletion...), all in order to avoid slicing and get the right type. Also, DoStuff::val should theorically not be null, but with a pointer there is no way I can prevent that (or atleast I don't know one). Maybe using smart pointers would help a bit here ? I am not super familiar with them.
I have to manage cases where T is a pointer and when it is not. For example, the deleteIfPointer function above, but also switching between . and -> and probably more.
Is there any simpler way to achieve what I am trying to do ? A design pattern or something else ? Am I stuck with my solution and is it somewhat good ?
Edit: I tried to implement it with std::variant as in #Tiger4Hire's answer:
class Derived : public Base
{
public:
Derived():b{10}{}
int b;
};
class Derived2 : public Base
{
public:
Derived2():c{12}{}
int c;
};
using DerivedTypes = std::variant<Derived, Derived2>;
struct VariantVisitor
{
void operator()(Derived& d)
{
d.b = 17;
}
void operator()(Derived2& d)
{
d.c = 17;
}
};
class DoStuffWithVariant : public DoStuff<DerivedTypes>
{
public:
void handleBasePart(Base& base)
{
cout << "a = " << base.a << endl;
base.a = 10;
}
virtual void printDoStuff() override
{
auto unionVal_l = getVal();
if (std::holds_alternative<Derived>(unionVal_l))
{
std::cout << "the variant holds a Derived!\n";
auto& derived_l = std::get<0>(unionVal_l);
cout << "b = " << derived_l.b << endl;
handleBasePart(derived_l);
}
else if (std::holds_alternative<Derived2>(unionVal_l))
{
std::cout << "the variant holds a Derived2!\n";
auto& derived2_l = std::get<1>(unionVal_l);
cout << "c = " << derived2_l.c << endl;
handleBasePart(derived2_l);
}
std::visit(VariantVisitor{}, unionVal_l);
}
};
What I like about it:
I don't have to use pointers.
I feel the code is less tricky, easier to understand.
What I don't like about it:
The code is all in one place and it deals with all the possible Derived types (and even the Base type) at once whereas with inheritance, classes are more specialized, you can really look at a class and directly know what it does, what it overrides etc... On the other hand one could argue that it means the algorithm is in one place instead of dispatched all over the classes hierarchy.
You can't have an abstract base class as your interface.
All in all it is a really good alternative, but I am still wondering if there is a simpler way to implement dynamic polymorphism ? Do you necessarily have to resort to (base class) pointers with dynamic polymorphism ? Are std::variant the way to go now ?
Edit2: 2 other drawbacks with variants that I didn't notice at first:
All your derived class and your base class have to be defined in the same library. Clients can't easily add a new Derived class since it would mean modifying the variant and they might not have access to it.
On the project I am working on, base classes are defined in one library, and are derived in other independant "sub" libraries. So if I try to use variant in my main library, it won't be able to access the Derived types in the sub libraries, which is a major issue.
If your base class implenting the variant (DoStuff here) has other members, when you call std::visit on the variant, you might have to also embark the needed other members of DoStuff. I think you should be able to use lambdas to capture them, but still, it's a lot less straightforward than using them directly as in the case of inheritance.
Your core problem is that you cast away your type information.
C++ will always call the right function, if it knows the correct type. This is why the pattern of pointer-to-base is almost always an anti-pattern (even though it is often taught as the "C++" way to do things).
Modern C++-style is to hold things as strongly-typed pointers, and cast them to the base pointer object, only when calling a function that takes a base-pointer as a parameter.
The standard supports this way of working by providing std::variant. Thus rather than
std::vector<Base*> my_list_of_things;
my_list_of_things.push_back(new Derived); // casting away type is bad
You start with
using DerivedTypes = std::variant<std::unique_ptr<Derived1>,
std::unique_ptr<Derived2>/*,etc*/>;
std::vector<DerivedTypes> my_list_of_things;
Now you can iterate over the list, calling a function which takes a pointer-to-base, casting away the type information only during the call.
You can also visit the members of the list, with a function (often a lambda) that knows exactly the type it is working on.
So you get the best of both worlds!
This does assume you have access to C++17 or above though, also that you are not working with code that is a library (compiled) but allows the library user to make their own classes. For example, libraries like Qt can't use this way of working.
If you don't have access to C++17, you may find curiously recursing templates fit much of what you are doing. (This is a controversial pattern though, as it is ugly and confusing)

Can a base class know if a derived class has overridden a virtual method?

The same question exists for C#, but does not apply to C++.
class Base
{
void dispatch()
{
if (newStyleHasBeenOverridden()) //how to find this out?
newStyle(42);
else
oldStyle(1, 2);
}
virtual void oldStyle(int, int) { throw "Implement me!"; }
virtual void newStyle(int) { throw "Implement me!"; }
}
class Derived:public Base
{
void newStyle(int) override
{
std::cout<<"Success!";
}
}
WARNING: This solution is not cross-platform in that it relies on a GCC extension and some undefined behavior.
GCC allows a syntax to grab the pointer to the function from the vtable of this by saying this->*&ClassName::functionName. It is probably not a good idea to actually use this, but here's a demo anyway:
#include <iostream>
class Base {
public:
void foo() {
auto base_bar_addr = reinterpret_cast<void*>(&Base::bar);
auto this_bar_addr = reinterpret_cast<void*>(this->*&Base::bar);
std::cout << (base_bar_addr == this_bar_addr ? "not overridden" : "overridden") << std::endl;
}
virtual void bar() { };
};
class Regular : public Base { };
class Overriding : public Base {
public:
virtual void bar() { };
};
int main() {
Regular r;
r.foo();
Overriding o;
o.foo();
}
And for posterity:
ICC allows the syntax, but it has a different meaning, which is the same as just saying &Base::bar, so you'll always think it isn't being overridden.
Clang and MSVC reject the code outright.
This is a design problem.
However, in the interest of answering the actual question, there are a couple ways you could accomplish this without a redesign (but really, you should redesign it).
One (terrible) option is to call the newstyle method and catch the exception that occurs if it's not overridden.
void dispatch() {
try {
newStyle(42);
} catch (const char *) {
oldStyle(1, 2);
}
}
If newStyle has been overridden, the override will be called. Otherwise, the base implementation will throw, which dispatch will catch and then fall back to oldStyle. This is an abuse of exceptions and it will perform poorly.
Another (slightly less terrible) approach is to make the base implementation of newStyle forward to oldStyle.
void dispatch() {
newStyle(42);
}
virtual void newStyle(int) { oldStyle(1, 2); }
virtual void oldStyle(int, int) { throw "implement me"; }
This at least moves in the direction of a better design. The point of inheritance is to allow high level code to be able to use objects interchangeably, regardless of their specialization. If dispatch has to inspect the actual object type, then you've violated the Liskov Substitution Principle. Dispatch should be able to treat all the objects the same way, and any differences in behavior should arise from the overridden methods themselves (rather than the existence of overrides).
Making things simpler, the dispatch decision is done by the Derived class. Abstract Base class is basically just an "interface" where the Derived class should implement all virtual functions.
The problem too sounded like an XY problem.
I thought this is what you want:
class Base // abstract class
{
virtual void oldStyle(int, int) = 0; // pure virtual functions
virtual void newStyle(int) = 0; // needs to be implemented
};
class Derived:public Base
{
public:
Derived(bool useNewStyle): _useNewStyle(useNewStyle) {}
void newStyle(int) { std::cout << "new style"; }
void oldStyle(int, int) { std::cout << "old style"; }
void dispatch()
{
if (_useNewStyle) {
newStyle(42);
return;
}
oldStyle(1, 2);
return;
}
private:
bool _useNewStyle = false;
};
Derived d(true); // use new style
d.dispatch(); // "new style"

Can the virtual function be found at runtime without calling?

I have a base class Base, with many derived classes (eg. Derived1, Derived2). Base has a pure virtual function fn, which is called many times using a Base pointer. Every time the function is called, I need to do some extra logging and related stuff. In particular, I use BOOST_CURRENT_FUNCTION in the derived-class functions to find out which function was called. Is there a way to know this information before calling the function, so that I do not have to rewrite the bookkeeping code in every derived function?
Edit: I wish to avoid writing __PRETTY_FUNCTION__ in each derived function.
#include <iostream>
using namespace std;
class Base {
public:
virtual void fn() = 0;
};
class Derived1:public Base {
public:
void fn() {
cout<<__PRETTY_FUNCTION__<<endl;
}
};
class Derived2:public Base {
public:
void fn() {
cout<<__PRETTY_FUNCTION__<<endl;
}
};
int main()
{
int choice =0;
Base *ptr1 = nullptr;
cout<<"Choose 0/1: "<<endl;
cin>>choice;
if(choice == 0) {
ptr1 = new Derived1;
}else {
ptr1 = new Derived2;
}
//********CAN I WRITE SOMETHING HERE, TO GIVE THE SAME RESULT?
ptr1->fn();
}
No, it cannot be. C++ does not support this kind of introspection. __PRETTY_FUNCTION__ is all you're gonna get.
From your description it seems you migth have a design issue. Have you considered using the template method design patter? The idea is to have your base class implement the common functionality and through virtual functions implement the specifics in your derived classes.
One idea is to implement the base pure virtual function and call it in each derived override. In the base one you increment a static counter. Something like:
#include <iostream>
#include <memory>
struct Base
{
static size_t counter;
virtual void f() = 0;
virtual ~Base() = default;
};
size_t Base::counter{0};
void Base::f() // IMPLEMENTATION, yes it's possible to implement a pure virtual function
{
++counter;
}
struct Derived1: Base
{
void f() override
{
Base::f(); // increment the counter
std::cout << "Derived1::f()\n";
}
};
struct Derived2: Base
{
void f() override
{
Base::f(); // increment the counter
std::cout << "Derived2::f()\n";
}
};
int main()
{
std::unique_ptr<Base> pBase1{new Derived1};
std::unique_ptr<Base> pBase2{new Derived2};
pBase1->f();
pBase1->f();
pBase2->f();
std::cout << Base::counter << std::endl; // outputs 3
}
Live on Wandbox
If I'm not wrong I believe this is an instance of the Template Method design pattern mentioned by #LordDosias. There is no other intrinsic way of getting this information out from the language, as C++ does not have genuine runtime reflection capabilities.
Well, aside from wrapping your macro in another macro that is smaller/shorter/does more, there is nothing that will provide the name of a function for you.
#define WHERE cout << __PRETTY_FUNCTION__ << endl
...
void fn() {
WHERE;
}
This also means you can turn on/off the tracing trivially:
#if TRACING
#define WHERE cout << __PRETTY_FUNCTION__ << endl
#else
#define WHERE
#endif
(You may want to wrap that in do { ... } while(0) in both sides to avoid problems if you were to put a WHERE inside an if, or some such, and still want it to work correctly when when it's "nothing")
The simplest answer is that, since C++ doesn't have auxiliary methods, you have to split the implementation of fn into a utility wrapper and the virtual function proper:
class Base {
protected:
virtual void fn_impl() = 0;
public:
void fn() { fn_impl(); }
};
class BaseWithLogging: public Base {
public:
void fn(); {
/* do logging */
fn_impl();
}
};
If you want the logs to capture the exact identity of the virtual (function name, file, line number, ...) which is actually, then there is no workaround for that; the boilerplate has to go into the function.
The crusty old preprocessor can be of help. E.g. simple-minded illustration:
#define LOG (cout<<__PRETTY_FUNCTION__<<endl)
and then you just have
LOG;
at the beginning of the function.

C++ private and protected virtual method

It seems that it is good to make the virtual methods private in order to separate the interfaces for following two clients -
1. clients that instantiate an object and call the method
2. clients that derive from the class and may want to override the method.
Simply put - the first client does not need to know if a method is virtual. He will call the base class public non-virtual method which in turn will call the private virtual method. See code below for example.
Now in the case where the virtual method needs to super-message its base class' corresponding virtual method such as say a Save method - which has to pass through all virtual methods in the chain of inheritance in order to save data corresponding to each level of derivation - we have no option but to use a protected virtual method - unless there is a way to guarantee saving of data at all levels of derivation without using super messaging (there is none that I know).
I would like to know if above reasoning correct.
Make sure you use the scroll to see the entire code.
#include <iostream>
using namespace std;
class A {
string data;
protected:
virtual void SaveData()= 0;
public:
A():data("Data of A"){}
void Save(){
cout << data << endl;
SaveData();
}
};
class B : public A {
string data;
protected:
virtual void SaveData() { cout << data << endl;}
public:
B():data("Data of B") {}
};
class C : public B {
string data;
protected:
virtual void SaveData() {
B::SaveData();
cout << data << endl;
}
public:
C():data("Data of C") {}
};
int main(int argc, const char * argv[])
{
C c;
c.Save();
return 0;
}
Yes, if you need to call the SaveData of another class, it needs to be accessible from that class - so public or protected.
You are exactly right:
NVI (Non-Virtual Interface) requires that virtual methods not be public
Calling the base class method requires that it not private
therefore protected is the obvious solution, at least in C++03. Unfortunately it means you have to trust the derived class developer not to forget to call "super".
In C++11, you can use final to prevent a derived class from overriding a virtual method; it means though that you are forced to introduce a new hook, example:
class Base {
public:
void save() {
// do something
this->saveImpl();
// do something
}
private:
virtual void saveImpl() {}
};
class Child: public Base {
private:
virtual void saveImpl() final {
// do something
this->saveImpl2();
// do something
}
virtual void saveImpl2() {}
};
Of course, there is the trouble of having to come up with a new name each and every time... but at least you are guaranteed that Child::saveImpl will be called because none of its children can override it.
It's difficult to tell what you're asking, but from the example, you do not need to make the method protected. It actually can be private. For details about the subtleties see this post: What is the point of a private pure virtual function?.
So long as you're not calling the private member from derived class (or outside classes), you're ok. Overriding of private members is ok. It does sound quite naughty and wrong that you can override your parent's privates, but in c++ you're allowed to do this.
The following should be ok:
#include <iostream>
using namespace std;
class A {
string data;
private:
virtual void SaveData()= 0;
public:
A():data("Data of A"){}
void Save(){
cout << data << endl;
SaveData();
}
};
class B : public A {
string data;
private:
virtual void SaveData() { cout << data << endl;}
public:
B():data("Data of B") {}
};

An elegant way to pass derived type to base member template function?

I have a class called 'ValueChecker'
which has the following member function:
template<typename T>
bool ValueChecker::checkMe( std::ostringstream &oss, T &me) {
std::cout << "Default checkMe() for " << typeid(me).name() << std::endl;
return true;
}
The class ValueChecker is intended to do some simple checks on the values of derived class. checkMe() will eventually get specialized for the different derived classes:
class Airplane : public ValueChecker {
friend class ValueChecker;
[...]
}
template<>
bool ValueChecker::checkMe<Airplane>( std::ostringstream &oss, Airplane &me) {
...
/* Actually, this code is generated from a simple file which translates
* a simple language into C++ code. So that a non-developer can write
* the simple checks.
*
* ValueChecker itself has utility functions that may be called in the
* template specialization which are shared across all types.
*/
}
This works, but there's just a small problem with the declaration of checkMe, when you look at the invocation:
int main() {
Airplane plane;
std::ostringstream oss;
if( plane.checkMe( oss, plane)) {
cout << "Values are bogus! " << oss.str() << endl;
return 0;
}
I call plane.checkMe(oss,plane). But, I could just as well pass another Airplane and not check plane. Furthermore, the invocation is redundant? Meaning, theoretically, the compiler should know which template function to call based on the plane's type. There shouldn't be a need to pass it in as an argument too? Anyways, it would be nice not to eliminate the last argument. So a call like this would be nice:
if( plane.checkMe(oss)) { ... } // Calls the right template specialization.
I just can't get it to work. Can the C++ guru's here help me out? thanks.
For your given code, you don't really need to use either template or friend. Instead use inheritance, and make the checkMe() method as protected and virtual method. Then override the checkMe() method in the derived class. If you do not need a default implementation, you could as well make it pure virtual. Here's a quick code snippet based on your example. (Note the use of this pointer.)
class ValueChecker {
protected:
virtual bool checkMe() {
std::cout << "Default checkMe() for " << typeid(this).name() << std::endl;
return true;
}
};
class Airplane : public ValueChecker {
public:
virtual bool checkMe() {
std::cout << "Airplane checkMe() for " << typeid(this).name() << std::endl;
return true;
}
};
int main() {
Airplane plane;
plane.checkMe();
}
You would need a default implementation when there's some "common" logic you want to use in one or more derived classes, in addition to the logic specific to the derived class itself. In that case, use the scope resolution operator to access the base class's logic.
bool Airplane::checkMe() {
std::cout << "Airplane checkMe() for " << typeid(this).name() << std::endl;
// use the "common" logic from the base class (if required)
ValueChecker::checkMe();
return true;
}
You might want to implement this as a pure virtual method.
class ValueChecker
{
public:
virtual bool checkMe(std::ostringstream& oss) = 0;
};
class Airplane : public ValueChecker
{
public:
virtual bool checkMe(std::ostringstream& oss);
};
That way you can just call plane.checkMe(oss) and the checkMe-Method of airplane will be called.
There's a common trick that is often done: http://en.wikipedia.org/wiki/Curiously_recurring_template_pattern
that could do the trick for you.