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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With