Multiple Instances of a class deriving from on instance of the SuperClass

Hi,

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.

Any help is appreciated.

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.
Last edited on
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.

Something a bit like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

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;
};
Alternatively you could group the common elements into a struct and keep one in each class.

A bit like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
struct std_info
{
protected:
    size_t id;
    std::string name;
    std::string bar_code;
};

class A
{
    std_info inf;
    double average;
    int sign;
    // ... etc... 
    // ... etc... 
    // ... etc... 
};

class B
{
    std_info inf;
    double qty;
};
Thanks Guys that helps a lot.
Topic archived. No new replies allowed.