'Is there any way to replace methods in super class without losing the old definition?
I'm trying to replace a function in super class A in order to extend its functionality in B class, but without losing the old definition. So is there any way to force the A::b method to use a new definition from B class? I have experience in Java, so I know it is possible in this language. Expected output is
A::b
B::a
A::a
Current output is
A::b
A::a
#include <iostream>
using namespace std;
class A {
protected:
static void a() {
cout << "A::a" << endl;
}
public:
void b() {
cout << "A::b" << endl;
a();
}
};
class B: public A {
protected:
static void a() {
cout << "B::a" << endl;
A::a();
}
};
int main()
{
B b;
b.b();
return 0;
}
Solution 1:[1]
I think you meant to use virtual keyword instead of static as shown below, since static in this context means that there is no implicit this parameter for the non-static member function a.
#include <iostream>
using namespace std;
class A {
protected:
virtual void a() { //note the virtual keyword
cout << "A::a" << endl;
}
public:
void b() {
cout << "A::b" << endl;
a();
}
};
class B: public A {
protected:
virtual void a() {//note the virtual keyword
cout << "B::a" << endl;
A::a();
}
};
int main()
{
B b;
b.b();
return 0;
}
The output of the above program can be seen here:
A::b
B::a
A::a
By using virtual we're making the member function a to be a virtual member funciton.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Anoop Rana |
