I have a program with a class (lets call it class A) that has very large data members. I also have another class (class B) that derives its data members from the data members in class A. I will also need more than one instant of class B. Does any body know of a way for multiple objects of class B to derive from one object of class A?
I thought about public inheritance, but every time I create an object of class B, an object of class A will be created also. I cannot afford to create more than one class A.
I thought about public inheritance, but every time I create an object of class B, an object of class A will be created also. I cannot afford to create more than one class A.
Then you need to redesign class A. Are there parts of class A that do not need to be duplicated for every object? Then you need to identify those parts and create a different class which the base class instance can have a pointer to. Derived classes always construct an instance of their base classes. The base class can also have static members but static member functions cannot be virtual.
Exactly my thoughts, as well. Consider using composition, rather than inheritance, to model a "has a", rather than an "is a", relationship. To limit the instances of the member, you could make it static or use the Singleton pattern.
Its difficult to know without having more details. From what I understand of what you said it might be worth you considering havinf both A and B derive from a common base class.
class D
{
protected:
size_t id;
std::string name;
std::string bar_code;
};
class A
: public D
{
double average;
int sign;
// ... etc...
// ... etc...
// ... etc...
};
class B
: public D
{
double qty;
};