Z
zero
I'm having trouble with overriding methods in subclasses. I'll explain
the problem using some code:
class BaseClass
{
protected:
void method2();
public:
void method1();
}
void BaseClass::method1()
{
// ...
method2();
// ...
}
void BaseClass::method2()
{
cout << "method2 of BaseClass";
}
class SubClas ublic BaseClass
{
private:
void method2();
}
void SubClass::method2()
{
cout << "method2 of SubClass"
}
int main()
{
SubClass s1;
s1.method1();
return 0;
}
ok, so I have method1 in the base class, which among other things calls
method2. The stuff that happens in method1 is the same for all
subclasses. However, what happens in method2 differs depending on the
subclass (although there is some common behaviour, the subclasses merely
extend method2). Now when I call method1 for the subclass, it should
give the behaviour of the subclass method2. But it does not - it uses
the baseclass method2. I understand why this is, and I have a solution
for it, but I'd like a better way.
The solution I use is just copying the whole method1 into every subclass.
This way the subclass method1 is called, which then calls the subclass
method2.
Is there any way I can code this better?
TIA
zero
the problem using some code:
class BaseClass
{
protected:
void method2();
public:
void method1();
}
void BaseClass::method1()
{
// ...
method2();
// ...
}
void BaseClass::method2()
{
cout << "method2 of BaseClass";
}
class SubClas ublic BaseClass
{
private:
void method2();
}
void SubClass::method2()
{
cout << "method2 of SubClass"
}
int main()
{
SubClass s1;
s1.method1();
return 0;
}
ok, so I have method1 in the base class, which among other things calls
method2. The stuff that happens in method1 is the same for all
subclasses. However, what happens in method2 differs depending on the
subclass (although there is some common behaviour, the subclasses merely
extend method2). Now when I call method1 for the subclass, it should
give the behaviour of the subclass method2. But it does not - it uses
the baseclass method2. I understand why this is, and I have a solution
for it, but I'd like a better way.
The solution I use is just copying the whole method1 into every subclass.
This way the subclass method1 is called, which then calls the subclass
method2.
Is there any way I can code this better?
TIA
zero