How can I add my own method to a pre-existing class without any change in context of pre-existing class.
for example :
A.hpp
class A
{
public :
void print1()
{
cout << "print1";
}
};
B.hpp
//add a helper function to class A
//for example:
A::print2()
{
cout << "print2";
}
main.cpp
#include "A.hpp"
#include "B.hpp"
main()
{
A a1;
a1.print2();
}
To extend a class in C++, distinguish two cases.
If the new function can be expressed in terms of the current interface, use non-member functions
// B.hpp
void print2(A const& a)
{
// pre-call extensions (logging, checking etc.)
a.print1();
// post-call extensions (logging, checking etc.)
}
If the new function requires knowledge about the current implementation, use class inheritance
// B.hpp
// WARNING: here be dragons, read on before using this in production code
class B: public A
{
public:
void print2() const // compiler-generated signature: void print2(B const*)
{
// pre-call extensions (logging, checking etc.)
print1();
// post-call extensions (logging, checking etc.)
}
};
However, deriving from a class that was not intended to be a base class, can be dangerous. In particular, if A does not have a virtual destructor, you can get into trouble if you ever use pointers to dynamically allocated B objects in places where they would be deallocated as if they were pointers to A objects.
Furthermore, because A::print1() was not made virtual, you get into all sorts of name hiding problems, which is why you have to name the extended function B::print2().
Long story short: know which kind of classes you are writing. If you want to extend the behavior based on a class implementation, then you better make it suitable as a base class (virtual destructor, virtual functions that you can override). Otherwise, mark your class as final (new C++11 contextual keyword). This will generate compiler warnings if you try to override existing functions.
NOTE: In other languages (notably D), it is possible to let the compiler automatically find non-member functions print2(a) when it sees the syntax a.print2(). Unfortunately, such uniform function call syntax is not on the roadmap yet for C++.
Related
I'm trying to use interface classes and I have the following class structure:
IBase.h:
#pragma once
class IBase
{
protected:
virtual ~IBase() = default;
public:
virtual void Delete() = 0;
IBase& operator=(const IBase&) = delete;
};
IQuackable.h:
#ifndef IQUACKABLE
#define IQUACKABLE
#include "IBase.h"
#include <iostream>
class IQuackable : public IBase
{
protected:
IQuackable() = default;
~IQuackable() = default;
public:
virtual void Quack() = 0;
static IQuackable* CreateInstance();
};
#endif //
MallardDuck.h:
#pragma once
#include "IQuackable.h"
class MallardDuck : public IQuackable
{
private:
MallardDuck();
protected:
~MallardDuck();
public:
void Delete() override;
void Quack() override;
friend IQuackable* IQuackable::CreateInstance();
};
MallardDuck.cpp:
#include "MallardDuck.h"
MallardDuck::MallardDuck() {}
MallardDuck::~MallardDuck() {}
void MallardDuck::Delete() { delete this; }
void MallardDuck::Quack()
{
std::cout << "Quack!\n";
}
IQuackable* IQuackable::CreateInstance()
{
return static_cast<IQuackable*>(new MallardDuck());
}
Also I've created class RedHeadDuck.h and .cpp with the same declaration and definition as MallardDuck.
And, finaly, main class code:
#include "MallardDuck.h"
#include "RedHeadDuck.h"
int main()
{
IQuackable* mallardDuck = MallardDuck::CreateInstance();
IQuackable* redHeadDuck = RedHeadDuck::CreateInstance();
mallardDuck->Quack();
redHeadDuck->Quack();
}
And here I got two errors:
LNK2005 "public: static class IQuackable * __cdecl IQuackable::CreateInstance(void)" (?CreateInstance#IQuackable##SAPAV1#XZ) already defined in MallardDuck.obj".
LNK1169 "one or more multiply defined symbols found".
As I find out, the problem is in double definition, but how it fix?
I've read about Header guards, but, as I understood, it can't help in this case. Also people write about inline functions, but I've not realized how it may be used here.
What can I do?
Goals
I suppose these are what you are trying to obtain by adopting all the complicated patterns:
interface, i.e., "multiple types, same set of methods"
some sort of abstract factory pattern, i.e., you want a "instantiator" who provides a static method (which is not very different from a global function) to call, and returns instances of derived classes
prohibit users from directly calling the ctors of derived classes
take care of the dtors by implementing the Delete() method
Requirement 1-3
There are at least 3 ways to meet requirement 1-3, as explained below:
1. Derived classes hiding static method of their base
This is the easiest way, and it's fully capable of current main.cpp. Derived classes can override static methods of their base class.
In file MallardDuck.h and RedHeadDuck.h:
// Replace this:
// friend IQuackable* IQuackable::CreateInstance();
// With this:
static IQuackable* CreateInstance();
In file MallardDuck.cpp (and RedHeadDuck.cpp similarly):
// Replace this:
// IQuackable* IQuackable::CreateInstance() {
// return static_cast<IQuackable*>(new MallardDuck());
// }
// With this:
IQuackable* MallardDuck::CreateInstance() {
return new MallardDuck();
}
The problem with this is that: other derived classes that don't override and hide CreateInstance() will still expose IQuackable::CreateInstance() as a "fallback". Thus:
if you don't actually implement IQuackable::CreateInstance() (so far, you don't have to), then once it is called via a derived class, the code won't compile and won't give a reason that's comprehensible to others; or
if you choose to implement it, you'd better throw an exception within it, which may surprise your user; otherwise you would have to return a nullptr or something, which is the worst practice in C++ (that's what we do in C since it has no language-level support for error handling; any C++ function that cannot fulfill its job should never return).
Either way is not elegant.
2. Adopt abstract factory pattern
This pattern requires a cooperating "factory class", which is abstract; then whenever you derive a concrete quackable, derive also its factory.
In your case you'll need to sketch out a IQuackableFactory, exposing IQuackableFactory::CreateInstance(), then derive a MallardDuckFactory and a RedHeadDuckFactory.
There are plenty of good examples already, so I won't demonstrate here.
3. Feature injection by using CRTP
There's yet another way of doing things. By CreateInstance() you're actually providing a "Give me an instance of this class!" feature. Typically we use the CRTP (curiously recurring template pattern) to "inject" a certain feature into a class.
First write this file EnableCreateInstance.hpp:
#ifndef _ENABLECREATEINSTANCE_HPP_
#define _ENABLECREATEINSTANCE_HPP_
template <class T>
struct EnableCreateInstance {
static T* CreateInstance() { return new T(); }
};
#endif //_ENABLECREATEINSTANCE_HPP_
Then in MallardDuck.h:
// Add:
#include "EnableCreateInstance.hpp"
class MallardDuck : public IQuackable, public EnableCreateInstance<MallardDuck> {
private:
MallardDuck();
friend class EnableCreateInstance<MallardDuck>;
...
In file RedHeadDuck.h do the similar: include header, publicly inherit EnableCreateInstance<RedHeadDuck>, and declare EnableCreateInstance<RedHeadDuck> as friend class.
This provides more flexibility: you're still providing an interface CreateInstance(), but in a less "aggressive" way: derived classes have their freedom to choose whether or not to provide CreateInstance(). If they do, just inherit and (if ctor made private) declare friendship; if not, omit the additional inheritance.
Requirement 4
Well, actually you can use delete this in non-static non-dtor method. But:
You must ensure (which can be difficult) that no more access to the deleted object's data members or virtual functions are made, otherwise it causes undefined behaviors;
You leave your users with dangling pointers to the deleted object.
So, we seldom provide such "deleters" in modern C++. You can get all the benefits it may provide through smart pointers, plus the ability to avoid UBs and so much more.
If you have a feature rich class, possibly one you do not own/control, it is often the case where you want to add some functionality so deriving makes sense.
Occasionally you want to subtract as well, that is disallow some part of the base interface. The common idiom I have seen is to derive and make some member functions private and then not implement them. As follows:
class Base
{
public:
virtual void foo() {}
void goo() { this->foo(); }
};
class Derived : public Base
{
private:
void foo();
};
someplace else:
Base * b= new Derived;
and yet another place:
b->foo(); // Any way to prevent this at compile time?
b->goo(); // or this?
It seems that if the compilation doesn't know that it is derived, the best you can do is not implement and have it fail at runtime.
The issue arises when you have a library, that you can't change, that takes a pointer to base, and you can implement some of the methods, but not all. So part of the library is useful, but you run the risk of core dumping if you don't know at compile time which functions will call what.
To make it more difficult, others may inherit from you class and want to use the library, and they may add some of the functions you didn't.
Is there another way? in C++11? in C++14?
Let's analyze this, focused on two major points:
class Base
{
public:
virtual void foo() {} // This 1)
// ...
class Derived : public Base // and this 2)
In 1) you tell the world that every object of Base offers the method foo() publicly. This implies that when I have Base*b I can call b->foo() - and b->goo().
In 2) you tell the world that your class Derived publicly behaves like a Base. Thus the following is possible:
void call(Base *b) { b->foo(); }
int main() {
Derived *b = new Derived();
call(b);
delete b;
}
Hopefully you see that there is no way call(Base*) can know if b is a derived and thus it can't possibly decide at compile-time if calling foo wouldn't be legal.
There are two ways to handle this:
You could change the visibility of foo(). This is probably not what you want because other classes can derive from Base and someone wants to call foo afterall. Keep in mind that virtual methods can be private, so you should probably declare Base as
class Base
{
virtual void foo() {}
public:
void goo() { this->foo(); }
};
You can change Derived so that it inherits either protected or private from Base. This implies that nobody/only inheriting classes can "see" that Derived is a Base and a call to foo()/goo() is not allowed:
class Derived : private Base
{
private:
void foo() override;
// Friends of this class can see the Base aspect
// .... OR
// public: // this way
// void foo(); // would allow access to foo()
};
// Derived d; d.goo() // <-- illegal
// d.foo() // <-- illegal because `private Base` is invisible
You should generally go with the latter because it doesn't involve changing the interface of the Base class - the "real" utility.
TL;DR: Deriving a class is a contract to provide at least that interface. Subtraction is not possible.
This seems to be what you want to do:
struct Library {
int balance();
virtual int giveth(); // overrideable
int taketh(); // part of the library
};
/* compiled into the library's object code: */
int Library::balance() { return giveth() - taketh(); }
/* Back in header files */
// PSEUDO CODE
struct IHaveABadFeelingAboutThis : public Library {
int giveth() override; // my implementation of this
int taketh() = delete; // NO TAKE!
};
So that you can't call taketh() on an IHaveABadFeelingAboutThis even when it is cast as the base class.
int main() {
IHaveABadFeelingAboutThis x;
Library* lib = &x;
lib->taketh(); // Compile error: NO TAKE CANDLE!
// but how should this be handled?
lib->balance();
}
If you want to present a different interface than the underlying library you need a facade to present your interface instead of the that of the library.
class Facade {
struct LibraryImpl : public Library {
int giveth() override;
};
LibraryImpl m_impl;
public:
int balance() { return m_impl.balance(); }
virtual int giveth() { return m_impl.giveth(); }
// don't declare taketh
};
int main() {
Facade f;
int g = f.giveth();
int t = f.taketh(); // compile error: undefined
}
Although I don't think your overall situation is good design, and I share many of the sentiments in the comments, I can also appreciate that a lot of code you don't control is involved. I don't believe there is any compile time solution to your problem that has well defined behavior, but what is far preferable to making methods private and not implementing them is to implement the entire interface and simply make any methods you can't cope with throw an exception. This way at least the behavior is defined, and you can even do try/catch if you think you can recover from a library function needing interface you can't provide. Making the best of a bad situation, I think.
If you have class A:public B, then you should follow the https://en.wikipedia.org/wiki/Liskov_substitution_principle
The Liskov substitution principle is that a pointer-to-A can be used as a pointer-to-B in all circumstances. Any requirements that B has, A should satisfy.
This is tricky to pull off, and is one of the reasons why many consider OO-style inheritance far less useful than it looks.
Your base exposes a virtual void foo(). The usual contract means that such a foo can be called, and if its preconditions are met, it will return.
If you derive from base, you cannot strengthen the preconditions, nor relax the postconditions.
On the other hand, if base::foo() was documented (and consumers of base supported) the possibility of it throwing an error (say, method_does_not_exist), then you could derive, and have your implementation throw that error. Note that even if the contract says it could do this, in practice if this isn't tested consumers may not work.
Violating the Liskov substitution principle is a great way to have lots of bugs and unmaintainable code. Only do it if you really, really need to.
Instead of using a virtual function, is it fine to use something like:
void BaseClass::functionName () { // BaseClass already has virtual functions
// some LONG code true for all derived classes of BaseClass
// ...
if (typeid (*this) == typeid (DerivedClass1))
// use functions of DerivedClass1 on dynamic_cast<DerivedClass1*>(this)
else if (typeid (*this) == typeid (DerivedClass2))
// use functions of DerivedClass2 on dynamic_cast<DerivedClass2*>(this)
// some LONG code true for all derived classes of BaseClass
// ...
}
It's just that I feel it's not a good idea to use virtual functions for something like the above when it is only a small section that is specialized for the derived classes. The long code that is used for all the derived classes will then need to be used over and over for all the derived classes (suggesting a helper function(s) just for that). Of course, I've tested my method and it works (and I suppose with no loss in performance), but I wonder if this is questionable practice.
What if the if-else-if part is used more than once in the function?
And if the common code for all derived classes is relavitively SHORT, then it is better to use virtual functions then, right?
Why not do this:
void BaseClass::functionName () {
// some LONG code true for all derived classes of BaseClass
// ...
this->some_protected_virtual_member_function();
// some LONG code true for all derived classes of BaseClass
// ...
}
So the common part is not duplicated and the behavior can still easily have extensions in your children classes without having to add another if to your parent class
Your code will not work at all unless the classes have virtual functions. C++ provides only limited reflection: typeid(DerivedClass1)==typeid(DerivedClass2) if there are no virtual functions. The above code also may be slower than simply accessing a virtual function: you'll get a new branch for each type rather than a constant time pointer lookup.
However, the biggest issue with the above code is that it looses polymorphism and encapsulation. The using code must be aware or what DerivedClass1 and DerivedClass2 need to do. It needs to be aware of the structures inside DerivedClass1 and DerivedClass2. Also, all the code is piled into one place, making this function possibly hundreds of lines.
I think you're looking for the template method pattern here: Just use your existing non-virtual function and have it call a virtual function only for the small section of code that differes between concrete classes. It has the advantage of looking prettier too.
void BaseClass::functionName () {
// some LONG code true for all derived classes of BaseClass
// ...
functionName_impl(); // Will be virtual (private or protected) and overriden in each child class to do the right work.
// some LONG code true for all derived classes of BaseClass
// ...
}
This is a degenerate case of the Template Method Pattern:
class Base {
public:
void templated() {
// do some stuff
this->hook1();
// other stuff
if (/*cond*/) { this->hook2(); }
size_t acc = 0;
for (Stuff const& s: /*...*/) { acc += this->hook3(s); }
// other stuff
}
private:
virtual void hook1() {}
virtual void hook2() {}
virtual size_t hook3(Stuff const&) { return 0; }
}; // class Base
And then a Derived class can customize the behavior of the hooks.
A word of warning: this is extremely rigid, by nature, since the templated method is not virtual; this is a both a virtue and a problem of this pattern, it is good because if you need to change the templated method then it is defined in a single place and it is annoying if the hooks provided are not sufficient to customize the behavior.
Preface:
This is a question about best practices regarding a new meaning of the delete operator introduced with C++11 when applied to a child class overriding an inherited parent's virtual method.
Background:
Per the standard, the first use case cited is to explicitly disallow calling functions for certain types where conversions would otherwise be implicit such as the example from §8.4.3 of the latest C++11 standard draft:
struct sometype {
sometype() = delete; // OK, but redundant
some_type(std::intmax_t) = delete;
some_type(double);
};
The above example is clear and purposeful. However, the following example where the new operator is overridden and prevented from being called by defining it as deleted started me thinking about other scenarios that I later identify in the question section (the example below is from §8.4.3 of the C++11 standard draft):
struct sometype {
void *operator new(std::size_t) = delete;
void *operator new[](std::size_t) = delete;
};
sometype *p = new sometype; // error, deleted class operator new
sometype *q = new sometype[3]; // error, deleted class operator new[]
Question:
By extension of this thought to inheritance, I am curious to other's thoughts regarding whether the following usage example is a clear and valid use-case or if it is an unclear abuse of the newly added feature. Please provide justification for your answer (the example that provides the most compelling reasoning will be accepted). In the example that follows, the design attempts to maintain two versions of library (the library is required to be instantiated) by having the second version of the library inherit from the first. The idea is to allow bug fixes or changes made to the first library version to automatically propagate to the second library version while allowing the second library version to focus only on its differences from the first version. To deprecate a function in the second library version, the delete operator is used to disallow a call to the overridden function:
class LibraryVersion1 {
public:
virtual void doSomething1() { /* does something */ }
// many other library methods
virtual void doSomethingN() { /* does something else */ }
};
class LibraryVersion2 : public LibraryVersion1 {
public:
// Deprecate the doSomething1 method by disallowing it from being called
virtual void doSomething1() override = delete;
// Add new method definitions
virtual void doSomethingElse() { /* does something else */ }
};
Though I can see many benefits to such an approach, I think I tend more toward the thought that it is an abuse of the feature. The primary pitfall I see in the above example is that the classic "is-a" relationship of inheritance is broken. I have read many articles that strongly recommend against any use of inheritance to express a "sort-of-is-a" relationship and to instead use composition with wrapper functions to clearly identify the relationships of the classes. While the following often-frowned-upon example requires more effort to implement and maintain (regarding the number of lines written for this piece of code, since every inherited function to be available publicly must be explicitly called out by the inheriting class), the use of delete as depicted above is very similar in many ways:
class LibraryVersion1 {
public:
virtual void doSomething1() { /* does something */ }
virtual void doSomething2() { /* does something */ }
// many other library methods
virtual void doSomethingN() { /* does something */ }
};
class LibraryVersion2 : private LibraryVersion1 {
// doSomething1 is inherited privately so other classes cannot call it
public:
// Explicitly state which functions have not been deprecated
using LibraryVersion1::doSomething2();
// ... using (many other library methods)
using LibraryVersion1::doSomethingN();
// Add new method definitions
virtual void doSomethingElse() { /* does something else */ }
};
Thank you in advance for your answers and further insight into this potential use-case of delete.
Paragraph 8.4.3/2 of the C++ Standard indirectly forbids deleting a function which overrides a virtual function:
"A program that refers to a deleted function implicitly or explicitly, other than to declare it, is ill-formed. [ Note: This includes calling the function implicitly or explicitly and forming a pointer or pointer-to-member to the function"
Invoking an overriding virtual function through a pointer to the base class is an attempt to implicitly invoke the function. Therefore, per 8.4.3/2, a design that allows this is illegal. Also notice that no C++11 conforming compiler will let you delete an overriding virtual function.
More explicitly, the same is mandated by Paragraph 10.3/16:
"A function with a deleted definition (8.4) shall not override a function that does not have a deleted definition. Likewise, a function that does not have a deleted definition shall not override a function with a deleted definition."
10.3p16:
A function with a deleted definition (8.4) shall not override a function that does not have a deleted definition. Likewise, a function that does not have a deleted definition shall not override a function with a deleted definition.
The other answers explain why pretty well, but there you have the official Thou Shalt Not.
Consider some function:
void f(LibraryVersion1* p)
{
p->doSomething1();
}
This will compile before LibraryVersion2 is even written.
So now you implement LibraryVersion2 with the deleted virtual.
f has already been compiled. It doesn't know until runtime which LibraryVersion1 subclass it has been called with.
This is why a deleted virtual isn't legal, it doesn't make any sense.
Best you can do is:
class LibraryVersion2 : public LibraryVersion1
{
public:
virtual void doSomething1() override
{
throw DeletedFunctionException();
}
}
I know that it's OK for a pure virtual function to have an implementation. However, why it is like this? Is there conflict for the two concepts? What's the usage? Can any one offer any example?
In Effective C++, Scott Meyers gives the example that it is useful when you are reusing code through inheritance. He starts with this:
struct Airplane {
virtual void fly() {
// fly the plane
}
...
};
struct ModelA : Airplane { ... };
struct ModelB : Airplane { ... };
Now, ModelA and ModelB are flown the same way, and that's believed to be a common way to fly a plane, so the code is in the base class. However, not all planes are flown that way, and we intend planes to be polymorphic, so it's virtual.
Now we add ModelC, which must be flown differently, but we make a mistake:
struct ModelC : Airplane { ... (no fly function) };
Oops. ModelC is going to crash. Meyers would prefer the compiler to warn us of our mistake.
So, he makes fly pure virtual in Airplane with an implementation, and then in ModelA and ModelB, put:
void fly() { Airplane::fly(); }
Now unless we explictly state in our derived class that we want the default flying behaviour, we don't get it. So instead of just the documentation telling us all the things we need to check about our new model of plane, the compiler tells us too.
This does the job, but I think it's a bit weak. Ideally we instead have a BoringlyFlyable mixin containing the default implementation of fly, and reuse code that way, rather than putting code in a base class that assumes certain things about airplanes which are not requirements of airplanes. But that requires CRTP if the fly function actually does anything significant:
#include <iostream>
struct Wings {
void flap() { std::cout << "flapping\n"; }
};
struct Airplane {
Wings wings;
virtual void fly() = 0;
};
template <typename T>
struct BoringlyFlyable {
void fly() {
// planes fly by flapping their wings, right? Same as birds?
// (This code may need tweaking after consulting the domain expert)
static_cast<T*>(this)->wings.flap();
}
};
struct PlaneA : Airplane, BoringlyFlyable<PlaneA> {
void fly() { BoringlyFlyable<PlaneA>::fly(); }
};
int main() {
PlaneA p;
p.fly();
}
When PlaneA declares inheritance from BoringlyFlyable, it is asserting via interface that it is valid to fly it in the default way. Note that BoringlyFlyable could define pure virtual functions of its own: perhaps getWings would be a good abstraction. But since it's a template it doesn't have to.
I've a feeling that this pattern can replace all cases where you would have provided a pure virtual function with an implementation - the implementation can instead go in a mixin, which classes can inherit if they want it. But I can't immediately prove that (for instance if Airplane::fly uses private members then it requires considerable redesign to do it this way), and arguably CRTP is a bit high-powered for the beginner anyway. Also it's slightly more code that doesn't actually add functionality or type safety, it just makes explicit what is already implicit in Meyer's design, that some things can fly just by flapping their wings whereas others need to do other stuff instead. So my version is by no means a total shoo-in.
Was addressed in GotW #31. Summary:
There are three main reasons you might
do this. #1 is commonplace, #2 is
pretty rare, and #3 is a workaround
used occasionally by advanced
programmers working with weaker
compilers.
Most programmers should only ever use #1.
... Which is for pure virtual destructors.
There is no conflict with the two concepts, although they are rarely used together (as OO purists can't reconcile it, but that's beyond the scope of this question/answer).
The idea is that the pure virtual function is given an implementation while at the same time forcing subclasses to override that implementation. The subclasses may invoke the base class function to provide some default behavior. The base cannot be instantiated (it is "abstract") because the virtual function(s) is pure even though it may have an implementation.
Wikipedia sums this up pretty well:
Although pure virtual methods
typically have no implementation in
the class that declares them, pure
virtual methods in C++ are permitted
to contain an implementation in their
declaring class, providing fallback or
default behaviour that a derived class
can delegate to if appropriate.
Typically you don't need to provide base class implementations for pure virtuals. But there is one exception: pure virtual destructors. In fact if your base class has a pure virtual destructor, it must have an implementation. Why would you need a pure virtual destructor instead of just a virtual one? Typically, in order to make a base class abstract without requiring the implementation of any other method. For example, in a class where you might reasonably use the default implementation for any method, but you still don't want people to instantiate the base class, you can mark only the destructor as pure virtual.
EDIT:
Here's some code that illustrates a few ways to call the base implementation:
#include <iostream>
using namespace std;
class Base
{
public:
virtual void DoIt() = 0;
};
class Der : public Base
{
public:
void DoIt();
};
void Base::DoIt()
{
cout << "Base" << endl;
}
void Der::DoIt()
{
cout << "Der" << endl;
Base::DoIt();
}
int main()
{
Der d;
Base* b = &d;
d.DoIt();
b->DoIt(); // note that Der::DoIt is still called
b->Base::DoIt();
return 0;
}
That way you can provide a working implementation but still require the child class implementer to explicitely call that implementation.
Well, we have some great answers already.. I'm to slow at writing..
My thought would be for instance an init function that has try{} catch{}, meaning it shouldn't be placed in a constructor:
class A {
public:
virtual bool init() = 0 {
... // initiate stuff that couldn't be made in constructor
}
};
class B : public A{
public:
bool init(){
...
A::init();
}
};