Is it possible in C++ to extend a class(add a method) in a different source file without editing the original source file where the class is written?
In obj-c it is possible by writing another #interface AbcClass (ExtCategory) ... #end
I got compile-time error(s) when I tried something like this:
//Abc.h
class Abc { //This class is from a 3rd party library....
// ...I don't want to edit its source file.
void methodOne();
void methodTwo();
}
//Abc+Ext.h
class Abc { // ERROR: Redefinition of 'Abc'
void methodAdded();
}
My target is to retain the 'Abc' name and add methods to it. A specific class in a 3rd party library that I used lacks some methods and I want to add those methods but I am keeping the source file unedited.
Is there a way to do this? I am new in writing C++ codes. I am familiar with some of its syntax but don't know much.
No. This kind of class extension is not possible in C++. But you can inherit a class from the original source file and add new functions in your source file.
//Abc.h
class Abc {
void methodOne();
void methodTwo();
};
//Abc+Ext.h
class AbcExt : public Abc {
void methodAdded();
};
You can then call methods as following:
std::unique_ptr<AbcExt> obj = std::make_unique<AbcExt>();
obj->methodOne(); // by the virtue of base class
obj->methodAdded(); // by the virtue of derived class
There's a way to actually do this, but it requires the compiler to support #include_next. GCC has this, no idea about other compilers. It also needs to support at least C++11.
I wouldn't exactly call this trick beautiful, but it does the job.
Ensure your include path has the the directory where the "extension" file resides before the directory where the original code resides (i.e. if the original Abc.hpp is in src, then move it to src/some_dir). So in this case your include dirs would be -Isrc -Isrc/some_dir.
Your "extension" code should be in a file with the exact same name as the original code. So for this example that's Abc.hpp.
Here's the extension file's content:
#ifndef ABC_EXT_HPP_
#define ABC_EXT_HPP_
#include <utility>
namespace evil {
// Search the include path for the original file.
#include_next "Abc.hpp"
}
class Abc : public evil::Abc {
public:
/*
// Inherit all constructors from base class. Requires GCC >=4.8.
using evil::Abc::Abc;
*/
/* Use the solution below if your compiler supports C++11, but not
* inheriting constructors.
*/
template <class... Args>
Abc (Args... args) : evil::ABC(std::forward<Args...>(args...)) { }
~Abc () { }
void methodAdded () { /* Do some magic. */ }
};
#endif // ABC_EXT_HPP_
There's things missing in the example such as the assignment operator not being "forwarded" to the base class. You can use the same trick as used for the constructor to do that. There might be other things missing, but this should give you a starting point which works well enough for "simple" classes.
One thing I dislike is the creation of the "evil" namespace. However, anonymous namespaces can't help out here, because a new anonymous namespace will be created in each translation unit that includes Abc.hpp. That will lead to issues if your base class has e.g. static members.
Edit: Nevermind, the assignment operator (i.e. Abc bla = evil::Abc(9)) also works, because evil:Abc can be implicitly converted to Abc because that constructor exists.
Edit 2: You might run into a lot of trouble once there's nested namespaces involved. This happens as soon as there's an #include in the original Abc.hpp, because it will now be nested inside the evil namespace. If you know all of the includes, you could include them before declaring the evil namespace. Things get real ugly, real quick though.
There's no specific mechanism for doing this directly in the current C++, but there are several ways you can achieve something like it at the cost of some boiler-plate work:
Method 1:
// foo.h
class Foo {
private: // stuff
public: // stuff
private:
// All this crap is private. Pretend like I didn't expose it.
// yeah, I know, you have to compile it, and it probably adds
// dependencies you don't want to #include, like <string>
// or boost, but suck it up, cupcake. Stroustrup hates life.
void internalHelper(std::string&, std::vector&, boost::everything&);
};
Method 2:
// foo.h
class Foo {
private: // stuff
public: // stuff
};
// fooimpl.h
// Internal file, do not export with the API.
class FooImpl : public Foo {
private: // stuff
public: // stuff
// So yeah, you have to go thru a cast and an extra include
// if you want to access this. Suck it up, cupcake.
void internalHelper(std::string&, std::vector&, boost::everything&);
};
Method 3:
// foo.h
class Foo {
private: // stuff
public: // stuff
// For the private api: this is the worst approach, since it
// exposes stuff and forces include/cruft on consumers.
friend void foo_internalHelper(std::string&, std::vector&, boost::everything&);
};
// foo.cpp
// don't make it static or anyone can make their own as a way to
// back door into our class.
void foo_internalHelper(...);
Method 4:
// foo.h
class Foo {
private: // stuff
public: // stuff
// No dependencies, but nothing stops an end-user from creating
// a FooPrivate themselves...
friend class FooPrivate;
};
// foo1.cpp
class FooPrivate {
public:
void fooInternalHelper(Foo* f) {
f->m_privateInternalYouCantSeeMe = "Oh, but I can";
}
};
You cannot extend the class Abc, period!
The only way out are freestanding functions like
Abc add(const Abc& a, int b);
i found out that c++ is better at doing this than obj-c.
i tried the following and it works great!
the key is, enclose all of your classes in a namespace and then extend your target classes there with the same class name.
//Abc.h
namespace LibraryA {
class Abc { //This class is from a 3rd party library....
// ...I don't want to edit its source file.
void methodOne();
void methodTwo();
}
}
//Abc+Ext.hpp
namespace MyProj {
class Abc : public LibraryA::Abc {
using Base = LibraryA::Abc; //desc: this is to easily access the original class...
// ...by using code: Abc::Base::someOrigMethod();
using Base::Base; //desc: inherit all constructors.
protected:
//---added members:
int memberAdded;
public:
//---added methods:
void methodAdded();
//---modified virtual member funcs from original class.
void origMethod_A() override;
}
}
//Abc+Ext.cpp
namespace MyProj {
void Abc::origMethod_A() {
//...some code here...
Base::origMethod_A(); //desc: you can still call the orignal method
//...some code here...
}
}
//SomeSourceFile_ThatUses_Abc.cpp
namespace MyProj { //IMPT NOTE: you really need to enclose your...
// ...project specific code to a namespace so you can...
// ...use the version of class Abc you extended.
void SomeClass::SampleFunc(){
Abc objX; //create MyProj::Abc object.
objX.methodAdded(); //calls MyProj::Abc::methodAdded();
objX.origMethod_A(); //calls MyProj::Abc::origMethod_A();
Abc::Base objY; //create Library::Abc object.
//objY.methodAdded(); //method not existing.
objY.origMethod_A(); //calls Library::Abc::origMethod_A();
//...some code here...
}
}
//SomeModule.cpp
namespace OtherNamespace {
void SomeOtherClass::SampleOtherFunc(){
Abc objZ; //create Library::Abc object.
//objZ.methodAdded(); //method not existing.
objZ.origMethod_A(); //calls LibraryA::Abc::origMethod_A();
}
}
you can even extend class Abc differently within other module namespaces.
//MyLib_ModuleA_Classes.hpp
namespace MyLib_ModuleA {
class Abc : public LibraryA::Abc {
//...add extensions here...
void addedMethod_X();
void origMethod_A() override; //own overriden behavior specific to this ModuleA only.
}
}
//MyLib_ModuleB_Classes.hpp
namespace MyLib_ModuleB {
class Abc : public LibraryA::Abc {
//...add extensions here...
void addedMethod_Y();
void origMethod_A() override; //own overriden behavior specific to this ModuleB only.
}
}
if in case class Abc is in global namespace, though i haven't tried it yet, i think you can just replace LibaryA::Abc to ::Abc.
sorry for the very late answer i've been doing this approach for around 4 years now and it's structure is very well useful.
i tried this in c++14 but i think this is still doable in c++11. now i used c++17 and it compiles fine. i'm planning to convert to c++20
when the compilers i used already completed c++20 features.
Related
I'm currently working on a project where everything is horribly mixed with everything. Every file include some others etc..
I want to focus a separating part of this spaghetti code into a library which has to be completely independent from the rest of the code.
The current problem is that some functions FunctionInternal of my library use some functions FunctionExternal declared somewhere else, hence my library is including some other files contained in the project, which is not conform with the requirement "independent from the rest of the code".
It goes without saying that I can't move FunctionExternal in my library.
My first idea to tackle this problem was to implement a public interface such as described bellow :
But I can't get it to work. Is my global pattern a way I could implement it or is there another way, if possible, to interface two functions without including one file in another causing an unwanted dependency.
How could I abstract my ExternalClass so my library would still be independent of the rest of my code ?
Edit 1:
External.h
#include "lib/InterfaceInternal.h"
class External : public InterfaceInternal {
private:
void ExternalFunction() {};
public:
virtual void InterfaceInternal_foo() override {
ExternalFunction();
};
};
Internal.h
#pragma once
#include "InterfaceInternal.h"
class Internal {
// how can i received there the InterfaceInternal_foo overrided in External.h ?
};
InterfaceInternal.h
#pragma once
class InterfaceInternal {
public:
virtual void InterfaceInternal_foo() = 0;
};
You can do like you suggested, override the internal interface in your external code. Then
// how can i received there the InterfaceInternal_foo overrided in External.h ?
just pass a pointer/reference to your class External that extends class InterfaceInternal. Of course your class Internal needs to have methods that accept InterfaceInternal*.
Or you can just pass the function to your internal interface as an argument. Something around:
class InterfaceInternal {
public:
void InterfaceInternal_foo(std::function<void()> f);
};
or more generic:
class InterfaceInternal {
public:
template <typename F> // + maybe some SFINAE magic, or C++20 concept to make sure it's actually callable
void InterfaceInternal_foo(F f);
};
Lets say I have a class with two member functions.
class Dummy {
public:
void procedure_1();
void procedure_2();
};
At compile time, I want to be sure that, procedure_1 is called before procedure_2. What is the correct way do implement this?
Maybe you could do it with a proxy-class. The idea is, that procedure_2 can't be accessed directly from outside (for example by making it private). procedure_1 would return some kind of proxy that allows the access to procedure_2.
Some code below, allthough I don't consider it clean or safe. And if you want, you can still break the system.
IMO such requirements should be handled without explicit validation, because it's quite cumbersome and impossible to make it absolutely safe.
Instead, the dependency should be well documented, which also seems idiomatic in C++. You get a warning that bad things might happen if a function is used incorrectly, but nothing prevents you from shooting your own leg.
class Dummy {
private:
void procedure_2() { }
class DummyProxy
{
private:
Dummy *parent; // Maybe use something safer here
public:
DummyProxy(Dummy *parent): parent(parent) {}
void procedure_2() { this->parent->procedure_2(); }
};
public:
[[nodiscard]] DummyProxy procedure_1() {
return DummyProxy{this};
}
};
int main()
{
Dummy d;
// d.procedure_2(); error: private within this context
auto proxy = d.procedure_1(); // You need to get the proxy first
proxy.procedure_2(); // Then
// But you can still break the system:
Dummy d2;
decltype(d2.procedure_1()) x(&d2); // only decltype, function is not actually called
d2.procedure_2(); // ooops, procedure_1 wasn't called for d2
}
Instead of "checking" it, just do not allow it. Do not expose an interface that allows to call it in any other way. Expose an interface that allows to only call it in specified order. For example:
// library.c
class Dummy {
private:
void procedure_1();
void procedure_2();
public:
void call_Dummy_prodedure_1_then_something_then_produre_2(std::function<void()> f){
procedure_1();
f();
procedure_2();
}
};
You could also make procedure_2 be called from destructor and procedure_1 from a constructor.
#include <memory>
struct Dummy {
private:
void procedure_1();
void procedure_2();
public:
struct Procedures {
Dummy& d;
Procedures(Dummy& d) : d(d) { d.procedure_1(); }
~Procedures() { d.procedure_2(); }
};
// just a simple example with unique_ptr
std::unique_ptr<Dummy::Procedures> call_Dummy_prodedure_1_then_produre_2(){
return std::make_unique<Dummy::Procedures>(*this);
}
};
int main() {
Dummy d;
auto call = d.call_Dummy_prodedure_1_then_produre_2();
call.reset(); // yay!
}
The above are methods that will make sure that inside one translation unit the calls will be ordered. To check between multiple source files, generate the final executable, then write a tool that will go through the generated assembly and if there are two or more calls to that call_Dummy_prodedure_1_then_produre_2 function that tool will error. For that, additional work is needed to make sure that call_Dummy_prodedure_1_then_produre_2 can't be optimized by the compiler.
But you could create a header that could only be included by one translation unit:
// dummy.h
int some_global_variable_with_initialization = 0;
struct Dummy {
....
};
and expose the interface from above into Dummy or add only the wrapper declaration in that library. That way, if multiple souce files include dummy.h, linker will error with multiple definitions error.
As for checking, you can make prodedure_1 and procedure_2 some macros that will expand to something that can't be optimized by the compiler with some mark, like assembly comment. Then you may go through generated executable with a custom tool that will check that the call to prodedure_1 comes before procedure_2.
Suppose I declare classes like this:
foo.h
namespace foo
{
class Data
{
public:
void reatain();
void release()
{
_refCnt--;
if(_refCnt == 0) _alloc->dealloc(_data);
}
int _refCnt;
Allocator *_alloc;
void *_data;
};
class Example
{
public:
// some functions
Data *_data;
};
}
bar.h
namespace bar
{
class Data
{
// declare the same with foo
};
class Example
{
public:
// some functions
/* except casting to foo::Example operator*/
operator foo::Example() const
{
foo::Example fooex;
fooex._data = reinterpret_cast<foo::Data *>(this->_data);
return fooex;
}
};
}
main.cpp
#include <foo.h>
#include <bar.h>
int main(void)
{
bar::Example barex;
foo::Example fooex = static_cast<foo::Example>(barex);
// do smt
return 0;
}
All classes are compiled in the same host, arch, compiler, etc.
I'd like to know with this implementation, is there any hidden bug inside it.
When foo:Example is deallocated. foo think his Data * is foo::Data * but actually, it's bar::Data *. Then it calls _data->release().
I don't know if there's any problem if I implement like this
I don't know how the compiler does.
2 classes are declared the same. So, someday will they cause an error if bar::Data is used as foo:Data ?
My opinion, the code is fragile, but should work. I'm under the impression field ordering and packing is largely consistent, but I don't believe that's actually a C++ spec thing.
What is more factual, is traditional malloc/free run only off the pointer base address. Also since you don't have a virtual destructor, your dealloc phase is simple enough to not be problematic. I can't comment what effect RTTI might have, I never became knowledgable in that area but it's worth considering.
What's important to point out is that you haven't identified what alloc/dealloc you are using, so the "traditional" method may have no application to you at all. My expectation is yours behaves traditionally.
I am working on a little game engine but I got stuck at something. Explanation : I have two classes, cEntity And ObjectFactory :
cEntity
class cEntity:public cEntityProperty
{
Vector2 position;
Vector2 scale;
public:
cEntity(void);
cEntity(const cEntity&);
~cEntity(void);
public:
void init();
void render();
void update();
void release();
};
ObjectFactory
#include "cEntity.h"
#include <vector>
class ObjectFactory
{
static std::vector<cEntity> *entityList;
static int i, j;
public:
static void addEntity(cEntity entity) {
entityList->push_back(entity);
}
private:
ObjectFactory(void);
~ObjectFactory(void);
};
std::vector<cEntity> *ObjectFactory::entityList = new std::vector<cEntity>();
Now I am adding new cEnity to ObjectFactory in cEntity constructor but facing an error related to circular references: for using ObjectFactor::addEntity() I need to define the ObjectFactory.h in cEntity class but it creates a circular reference.
I think your code might have an underlying architectural issue given how you have described the problem.
Your ObjectFactory should be handling the cEntities, which in turn should be unaware of the "level above". From the description of the problem you are having, it implies that you're not sure what class is in charge of what job.
Your cEntitys should expose an interface (i.e. all the stuff marked "public" in a class) that other bits of code interact with. Your ObjectFactory (which is a bit badly named if doing this job, but whatever) should in turn use that interface. The cEntitys shouldn't care who is using the interface: they have one job to do, and they do it. The ObjectFactory should have one job to do that requires it to keep a list of cEntitys around. You don't edit std::string when you use it elsewhere: why is your class any different?
That being said, there's two parts to resolving circular dependencies (beyond "Don't create code that has circular dependencies in the first place" - see the first part to this answer. That's the best way to avoid this sort of problem in my opinion)
1) Include guards. Do something like this to each header (.h) file:
#ifndef CENTITY_H
#define CENTITY_H
class cEntity:public cEntityProperty
{
Vector2 position;
Vector2 scale;
public:
cEntity(void);
cEntity(const cEntity&);
~cEntity(void);
public:
void init();
void render();
void update();
void release();
};
#endif
What this does:
The first time your file is included, CENTITY_H is not defined. The ifndef macro is thus true, and moves to the next line (defining CENTITY_H), before it moves onto the rest of your header.
The second time (and all future times), CENTITY_H is defined, so the ifndef macro skips straight to the endif, skipping your header. Subsequently, your header code only ever ends up in your compiled program once. If you want more details, try looking up how the Linker process.
2) Forward-declaration of your classes.
If ClassA needs a member of type ClassB, and ClassB needs a member of type ClassA you have a problem: neither class knows how much memory it needs to be allocated because it's dependant on another class containing itself.
The solution is that you have a pointer to the other class. Pointers are a fixed and known size by the compiler, so we don't have a problem. We do, however, need to tell the compiler to not worry too much if it runs into a symbol (class name) that we haven't previously defined yet, so we just add class Whatever; before we start using it.
In your case, change cEntity instances to pointers, and forward-declare the class at the start. You are now able to freely use ObjectFactory in cEntity.
#include "cEntity.h"
#include <vector>
class cEntity; // Compiler knows that we'll totally define this later, if we haven't already
class ObjectFactory
{
static std::vector<cEntity*> *entityList; // vector of pointers
static int i, j;
public:
static void addEntity(cEntity* entity) {
entityList->push_back(entity);
}
// Equally valid would be:
// static void addEntity(cEntity entity) {
// entityList->push_back(&entity);}
// (in both cases, you're pushing an address onto the vector.)
// Function arguments don't matter when the class is trying to work out how big it is in memory
private:
ObjectFactory(void);
~ObjectFactory(void);
};
std::vector<cEntity*> *ObjectFactory::entityList = new std::vector<cEntity*>();
I have written a library (doesn't matter what it does), which obviously has its header file. Now, I want to hide private elements of that header file, so if I provide my library to somebody, he/she should only see public members (preferably no class definition, nothing other than function definitions). One way would be creating C-style header, which will contain some kind of "init" method which will be used to create an instance of the actual class of library and the user will have to pass a pointer of that object to every function to do the job.
Is it a good practice?
Are there any other publicly accepted ways of doing something like that?
Thanks in advance.
In addition to the Factory pattern (which, in my opinion, can become unwieldy), you can also hide your private members behind a PIMPL (Pointer to IMPLementation):
// Interface.hpp
class Implementation;
class Interface {
public:
Interface() : pimpl(new Implementation()) {}
void publicMethod();
private:
std::unique_ptr<Implementation> pimpl;
};
// Interface.cpp
class Implementation {
public:
void PrivateMember();
};
void Interface::publicMethod() { pimpl->PrivateMember(); }
This has the advantage of hiding implementation, at the cost of a single pointer indirection, not much different from the typical inheritance-based Factory pattern.
This can also be ABI stable. Changes to your implementation won't affect linkage, since no changes will ever be visible to the rest of the program. This is a good pattern to use when implementing shared objects, for example.
It's also a common C++ idiom, so other C++ programmers will recognize it without question.
In the case of a class which will follow the Singleton pattern, you can avoid exposing the PIMPL at all, and simply write the entire implementation in an anonymous namespace in your .cpp file, where you can put as much state and private functions as you wish, without even hinting at it in your interface.
You can create a publicly-visible interface. Create an abstract class with the functions you want to expose, then have your implementation extend it.
For example, an interface:
class Interface {
public:
virtual void publicMethod() = 0;
...
};
And the implementation:
class Implementation : Interface {
public:
virtual void publicMethod();
private:
int hiddenMethod();
};
Then you only export the symbols for Interface. Now, in order for the user of the library to get instances of Interface which are actually Implementations, you need to provide a factory:
class Factory {
public:
//can create and return an Implementation pointer, but caller will get an Interface pointer
std::shared_ptr<Interface> getImplementationInstance();
}
Base on Eric Finn's answer, you can just declare an interface class to hold all your public methods which considered to be your API, and hide all implementations and private members/methods in implementation class which inherits interface class, here's the example:
Your header file: my_api.h
// your API in header file
// my_api.h
class interface {
public:
static interface* CreateInstance();
virtual void draw() = 0;
virtual void set(int) = 0;
};
your implementation(shared library): my_api.cpp (users won't see this when you make it a shared library)
So you can hide all your implementation and private methods/members here
#include "my_api.h"
// implementation -> in .cc file
class implementation : public interface {
int private_int_;
void ReportValue_();
public:
implementation();
void draw();
void set(int new_int);
};
implementation::implementation() {
// your actual constructor goes here
}
void implementation::draw() {
cout << "Implementation class draws something" << endl;
ReportValue_();
}
void implementation::ReportValue_() {
cout << "Private value is: " << private_int_ << endl;
}
void implementation::set(int new_int) {
private_int_ = new_int;
}
interface* interface::CreateInstance() {
return new implementation;
}
How user uses your API:
#include <iostream>
#include "my_api.h"
int main(int argc, const char * argv[])
{
using namespace std;
interface* a; interface* b;
a = interface::CreateInstance();
a->set(1);
b = interface::CreateInstance();
b->set(2);
b->draw();
a->draw();
return 0;
}
Output:
Implementation class draws
Private int is: 2
Implementation class draws
Private int is: 1
In this pattern, your api is just an abstract class which works like a factory, you can also implement the virtual method in different classes and specify which instance you would like to call.
I think you need to create Dynamic Link Library (dll).
Please take a quick look at this link:
You might want to take a look at the envelope/letter idiom, bridge design pattern, or proxy pattern. Basically, you would create an outer (public) class that would just forward your public method calls to the inner (private) class. Your InnerClass.h header only needs to be visible/known to your OuterClass.cpp and InnerClass.cpp source files.
Each of these patterns provides a mechanism of separating the implementation from the interface so that the caller is not coupled to the implementation. Sometimes this is desired to reduce compiler dependencies on large C++ projects. Another common reason for wanting to do this is just when you want to hide the implementation details so that the caller only sees a single opaque pointer.
======= OuterClass.h =====
class InnerClass; // forward declaration is all that's needed
class OuterClass {
private:
InnerClass *pInner;
public:
InnerClass();
bool doSomething();
};
======= OuterClass.cpp ======
#include "OuterClass.h"
#include "InnerClass.h"
OuterClass::OuterClass() :
pInner(new InnerClass())
{
}
bool OuterClass::doSomething()
{
return pInner->doSomething();
}
There actually is a way to do this without having to use classes. I had the same issue and here is a very simple solution:
Just put your private things into the .cpp file. Your header file will look something like this:
// These will be visible to everyone using this library
void function();
int someNumber = 2;
and your .cpp file:
void function() {
// whatever this function does
}
// This will be only visible to the library itself
static void secretFunction() {
doSomeSecretStuff;
}
static int PIN = 1234;
// Okay, if you write this Number into your library and expect it to be safe,
// then screw you, but at least no one will be able to access it with code
When calling the "public" functions from outside you now don't need any instance of that class anymore: Just place the library in the correct directory and include it, but you probably have already taken care of that) and call the functions by their names in the Lib.h file. In the instance of this example it would look something like this:
#include "Lib.h"
int main(int argc, const char * argv[]) {
function();
return 0;
}
Thanks to Edgar Bonet for helping me find this solution on the Arduino Stackexchange!