Reputation: 651
Hello I've got a class in some header file. Let's say it looks like this:
class MyClass
{
private:
int ID;
void method1();
public:
MyClass(int ID){this->ID = ID;};
void method2();
}
EDIT: I need two objects, which both has the same structure as MyClass + have some of their own methods (all of them won't have any parameters and will be returning void - like method1(), but with different implementation). I also need to have defined type, that can point at the new methods created here. So I can pass them into some another function as one type. The last thing I need is to get access to MyClass's attributes and methods from the new methods.
Upvotes: 2
Views: 1431
Reputation: 344
What you are probably looking for is inheritance. Basically you create a parent class (usually referred to as base class) and a child class, which inherits (therefore inheritance) members and functions from their base class.
// Base class
class BaseClass
{
public:
int GetNumber() { return 10; }
};
// Child class
class ChildClass: public BaseClass // public BaseClass means that this class inherits from other class
{
public:
string GetString() { return "Your string"; }
};
In this example, BaseClass has only one function, while ChildClass will have two function, one that is written into it, and one that it inherited. Here is an example.
BaseClass base;
base.GetNumber(); // Base class only has 1 function
ChildClass child;
child.GetNumber(); // It has inherited function
child.GetString(); // It also has its own function, which base class doesn't have
You can read a very in depth tutorial about inheritance in this here: http://www.cplusplus.com/doc/tutorial/inheritance/
Upvotes: 0
Reputation: 73366
There is no way to add a new method to an existing class without changing this class.
If you want to work with an enriched class adding just new methods method, all you need to do is:
class MyEnrichedClass : public MyClass {
public:
MyEnrichedClass (int ID) : MyClass(ID) {}
void myNewFantasticMethod (...) { ... }
};
In your added methods you have access to all public and protected members of your base class (but not the private ones).
If you know in advance that you need a method with a well defined signature and for a particular purpose, but you want to define it dynamically, you could have a function object as member and have your method call this function object (or function pointer if you prefer). But your dynamic function would not have access neither to private nor to protected members.
Upvotes: 2