Click here to Skip to main content
15,860,844 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)

Hi all,

I have a class, say GeneralBuilding, which could be one of the classes SmallBuilding, MediumBuilding, LargeBuilding, etc...., depending on the parameters passed to the Building constructor. SmallBuilding, MediumBuilding, and LargeBuilding have a common base class Building.

Is it possible that when I execute

GeneralBuilding x(1) // 1 bedroom...

that x is of a form chosen by the constructor depending on the constructor parameters (i.e. for sake of argument if no. bedrooms = 1 then x would be of class type SmallBuilding, if bedrooms = 2 then x would of type MediumBuilding, and if bedrooms >= 3 then d would be of type LargeBuilding) ?

The reason I'm interested in this is that I need the functionality for each type of GeneralBuilding to change depending on the building size, and I am trying to avoid a bunch of "if then" statements within one class. I'd like to spread the responsibilty to make the classes clean, tidy, safer, more maintainable etc.

I'm looking into it now...

Paul

Posted
Updated 25-Aug-09 10:07am
v2

1 solution

No, you can't select the type of the class this way. However, by using pointers (or references), you can manipulate all buildings the same way by manipulating pointers to the base class (this is called polymorphism, google for it if you want more information).

What you want are virtual constructors, but such mechanisms are not available in C++. Here's the short version of why there are no such things in C++: http://www.research.att.com/~bs/bs_faq2.html#virtual-ctor

What you could is delegate the instanciation of the class to an external class (a factory class), which will take care of creating the correct type depending of the parameter and will return a pointer to the base class. That's how it is done in general.
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900