class design woes
<p>I'd like to get some advice on designing classes in a situation similar to the example below. B and C objects may or may not have a number component. The problem is that there is no way to selectively call a NumberComponent constructor. Is there a better way to design this?</p>

<pre><code>class NumberComponent
{
public:
//Objects which don't have a number component just store a null pointer.
//Any time we do anything here, we have to make sure p_int isn't null.
NumberComponent() : p_int(0) { }
NumberComponent(int x) { p_int = new int(x); }
~NumberComponent() { delete p_int; }

void DoSomething() { if(p_int) ++(*p_int); }

//In real situation, this will be another complex class object.
//Using an int* here to keep this class simple for example.
int* p_int;
};

//B objects may or may not have a number component.
class B : public NumberComponent
{
public:
//If hasNumberComponent is false, we'd like to call the default constructor.
//If hasNumberComponent is true, we'd like to call NumberComponent(int) constructor.
B(int x, bool hasNumberComponent) {}

int value;
};

//C objects may or may not have a number component.
class C : public NumberComponent
{
public:
//If hasNumberComponent is false, we'd like to call the default constructor.
//If hasNumberComponent is true, we'd like to call NumberComponent(int) constructor.
C(int x, bool hasNumberComponent) {}

int value;
};

int main()
{
//myList contains NumberComponent* to B and C objects 
std::list&lt;NumberComponent*&gt; myList;

myList.push_back(new B(5, true));
myList.push_back(new C(3, true));

for(std::list&lt;NumberComponent*&gt;::iterator i = myList.begin(); i != myList.end(); ++i)
    (*i)-&gt;DoSomething();

//These objects don't have a Number component.
B b(2, false);
C c(1, false);

return 0;
}
</code></pre>
