Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add a method to existing C++ class in other file

Tags:

c++

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.

like image 305
acegs Avatar asked Sep 14 '13 17:09

acegs


1 Answers

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 
like image 200
Manoj Awasthi Avatar answered Sep 20 '22 09:09

Manoj Awasthi