R
Ruben Van Havermaet
Hi,
I have a problem using member functions in derived classes that
override virtual member functions of base classes.
The following pieces of (simplified) code don't work. Can anybody give
me some hints on what might be wrong?
// BEGIN OF SAMPLE CODE
class Strategy
{
public:
Strategy() {}
virtual void run() { cout<<"Please override!"; }
};
class StrategyA: public Strategy
{
public:
StrategyA() {}
void run();
};
void StategyA::run()
{
cout <<"Functionality A";
}
class SomeClass
{
public:
SomeClass(Strategy s);
void doSomething();
private:
Strategy s_;
};
SomeClass::SomeClass(Strategy s): s_(s) {}
SomeClass::doSomething()
{
s_.run();
}
int main()
{
StategyA s;
SomeClass c(s);
c.doSomething();
return 0;
}
// END OF SAMPLE CODE
The above program will print out "Please override!" instead of
"Functionality A". Scanning through Stroustrup I can't seem to find
what is wrong.
An additional remark: I know it is better to declare the function
"run" in Strategy to be pure virtual (virtual void run() = 0
but
that won't compile. The compiler gives error in SomeClass' constructor
and private member declaration. What do I forget?
Thanks In Advance,
With Kind Regards
Ruben Van Havermaet.
I have a problem using member functions in derived classes that
override virtual member functions of base classes.
The following pieces of (simplified) code don't work. Can anybody give
me some hints on what might be wrong?
// BEGIN OF SAMPLE CODE
class Strategy
{
public:
Strategy() {}
virtual void run() { cout<<"Please override!"; }
};
class StrategyA: public Strategy
{
public:
StrategyA() {}
void run();
};
void StategyA::run()
{
cout <<"Functionality A";
}
class SomeClass
{
public:
SomeClass(Strategy s);
void doSomething();
private:
Strategy s_;
};
SomeClass::SomeClass(Strategy s): s_(s) {}
SomeClass::doSomething()
{
s_.run();
}
int main()
{
StategyA s;
SomeClass c(s);
c.doSomething();
return 0;
}
// END OF SAMPLE CODE
The above program will print out "Please override!" instead of
"Functionality A". Scanning through Stroustrup I can't seem to find
what is wrong.
An additional remark: I know it is better to declare the function
"run" in Strategy to be pure virtual (virtual void run() = 0
that won't compile. The compiler gives error in SomeClass' constructor
and private member declaration. What do I forget?
Thanks In Advance,
With Kind Regards
Ruben Van Havermaet.