2

In the class below there is a pointer model_ of type OpModel which is a class. This pointer is initialized in the constructor using new to create an OpModel object. That's fine, you have a pointer to a valid object. The method model() deferences this pointer which access the actual OpModel object. But what I don't understand is that it returns a reference to CompositionalModel which is a different class.

I believe that it is related to polymorphism because OpModel is derived from CompositionalModel, which is an abstract class. But why would you return a reference to the base class?

ariane cathal
  • 85
  • 1
  • 6
  • 1
    Hopefully, whatever book/site you're using will get you where smart pointer (or no pointer) are the flavor of the day. That aside, yes, it's an OOP thing. the answer below is accurate. – WhozCraig Aug 08 '18 at 15:19

1 Answers1

4

This is quite a typical thing to do in OO code.

By returning the narrower, base class - think interface - the calling code need only know aboout that. You can hide all kinds of extra gory, implementation details that way. Otherwise, any calling code needs to know all about CompositionalModel.

Furthermore, this can change the OpModel to any other type of CompilationUnit and the calling code won't need to change.

doctorlove
  • 18,872
  • 2
  • 46
  • 62