What's wrong with the following code snippet


What's wrong with the following code snippet?Thanks!
Shape is the base class and Rectangle is the derived class.
1
2
3
  void SomeFunction (Shape);
Shape * pRect = new Rectangle;
SomeFunction(*pRect);
There is nothing wrong in this code snip. Only it is possible that the user will get the result he was not awaiting.:)
You haven't told us what the problem is, what your expected behaviour is, or what the observed behaviour is.

My guess is that you're seeing the call on line 3 treating the input as a Shape and you're expecting it to be treated as a Rectangle.

This is because you're passing in by value, which means that in the call to SomeFunction, you're creating an actual Shape object. The object that the code inside SomeFunction operates on is not actually a Rectangle - it's just a Shape.

What you want to do is redefine SomeFunction so that it takes either a reference to Shape, or a pointer to Shape. Then you'll see the polymorphic behaviour you're expecting.
Last edited on
So if it's a pointer to Shape, can I still call the function in Rectangle? Thanks!
Only if the functions you are going to call are declared in Shape or you will explicitly cast an object to type Rectangle inside the function.
1
2
3
  void SomeFunction (Shape); //a function that does nothing
Shape * pRect = new Rectangle; //declareing and initializing shape pointer
SomeFunction(*pRect); //a call to the function that does nothing 


I think the problem is that your code does not do anything
Topic archived. No new replies allowed.