Override virtual member functions in Subclasses

  • Thread starter Ruben Van Havermaet
  • Start date
R

Ruben Van Havermaet

SomeClass' data member is a Strategy, not a StrategyA. If you changed this
to

StrategyA s_;

Then it will work.

But what if I would want to use some other Strategy? What I really
intended to find out was how to implement "late binding of a function
call" or polymorphism.
(Stroustrup, "The C++ Programming Language", p. 312). The key to this,
as Victor pointed out, is to use references and pointers.
Declaring a pure virtual function makes the class an ADT (abstract data
type). Because you cannot create an object of an ADT, it must have a
default constructor (but that's already there). The problem comes from
trying to give SomeClass a Strategy member. When you do this, a Strategy
object is "constructed" inside SomeClass, which is an error. The SomeClass
constructor error is basically the same; it comes from trying to initialize
an object of the Strategy ADT.

But making it a reference clears this problem out of the way.


Friendly Greetings,
Ruben.
 
J

jeffc

Ruben Van Havermaet said:
The above program will print out "Please override!" instead of
"Functionality A". Scanning through Stroustrup I can't seem to find
what is wrong.

You can only have polymorphism with dynamic binding. In other words, all
your variables (created objects) are created statically and passed by value.
So the compiler will never defer the function calls to runtime. You would
need to use pointers or references to use polymorphism.
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?

You are passing the type by value. When you pass by value, you create a new
copy of the object. How can you create a new copy of a Strategy object if
the class is an abstract class? Again, you'd have to pass by pointer or
reference so the compiler doesn't try to make a copy of the object.
 
J

jeffc

Ruben Van Havermaet said:
Declaring the Strategy class to be abstract now also works. I assume
that this is because

Strategy& strat

in the private member declaration of SomeClass, doesn't need to be
constructed.

That and the fact that you're not passing it by value in the function call.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,774
Messages
2,569,596
Members
45,143
Latest member
DewittMill
Top