Let's say we have a class that has a function foo() that counts to 3 and we want from another class to be able to modify this function and after modifying it counts to 3 that was previously declared but also executes the new code too. The function foo() would only be called by class1 and i dont want to use inheritance. The new code that im supposed to add lets say it doesnt have any relationship with class1.
For Example:
#include <iostream>
using namespace std;
class class1 {
public:
class1()
{
}
void foo()
{
for(int i =0;i<2;i )
{cout << i << endl;}
}
};
class class2 {
public:
class2()
{
}
void foo() override
{
Super::foo();
cout << "Jump from a cliff" << endl;
}
};
int main()
{
class1 c1 = class1();
class2 c2 = class2();
c1.foo();
return 0;
}
Result:
0
1
2
Jump From a cliff
CodePudding user response:
You need an object to call a non-static member function.
If you want to get desired output from class2::foo
you can implement it for example like this:
class class2 {
public:
void foo()
{
class1 x;
x.foo();
cout << "Jump from a cliff" << endl;
}
};
Alternatively class1
can have a member of type class1
.
CodePudding user response:
Found the solution on Array of function pointers.