Ken
Ken

Reputation: 147

c++ return subclass where function returns pointer to superclass

I am new to c++. I attached a uml diagram of what i have, my issue is with returning a class defined as a superclass, but i will actually be returning a class that extends it.

In the uml diagram, the superclass in question is Booking and the subclasses Single and Sharing which extend it. I have a function addBooking([...]) in BookList class, which is where my issue is. enter image description here

I defined Booking, and then 2 other subclasses which extend it being Single and Sharing. My question is, can I return Single or Sharing class in the BookingList.addBooking([....]) function? Both my subclasses initialise the super class, for example Single initialises it like this:

Single::Single(Person c, QDate a, QDate d, Person g): Booking(c, a, d){[...]}

Upvotes: 1

Views: 1521

Answers (1)

DigitalEye
DigitalEye

Reputation: 1565

Yes, you may. Single and Sharing are of type Booking so returning a pointer to an instance of Single or Sharing as pointer to an instance of type Booking is completely legal.

Upvotes: 1

Related Questions