Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I have static data members in an abstract class?

I designed a series of related classes, and in order to be able to manage them I made them derive from a single abstract class.

These classes all need access to a series of shared resources, and I found myself creating a vector of pointers in each, all of them identical (they necessarily must be). It seems like making a static member in the base class would give all of the derived classes access to this vector, meaning I need only build it once (it's not going to change either after it's been built, just looked up).

My question is if this is ok, and if so, how can I then build it, without calling a 'fill the vector' method from one of the derived classes?

My thinking was to do something like

class Resource {};

enumR {RES0, RES1};

class AbstractClass
{
    public:
        virtual void OnInit() = 0;
        void static fillVector(Resource* pResource, enumR Resourcename)
            {lResource[Resourcename]=pResource;};
    protected:
        static vector<Resource*> lResource;
};

vector<Resource*> AbstractClass::lResource;

int main()
{
    Resource res0, res1;
    AbstractClass::fillVector(&res0, RES0);
    AbstractClass::fillVector(&res1, RES1);

    return 0;
};

Then when I instantiate an object of any class derived from AbstractClass, I'd have access to the lResource vector, which is what I want.

Would this work? Is it horrible? Is it ok?

like image 277
Kian Avatar asked Nov 13 '22 21:11

Kian


1 Answers

It would work, where work = compile & run.

However, all child classes will be accessing the same static vector, which means there won't be a different copy of the static vector for each child class.

For a better explanation of what I mean read the following So thread:

Are static fields inherited?

SOLUTION:

One solution is to have your parent class a template class as follows:

template<T>
class Parent<T> {
    public:
        static std::vector<T> sharedResource_;
}

class ChildA : Parent<ChildA> {
}

class ChildB : Parent<ChildB> {
}

In the above code, you will get a shared resource for all instances of ChildA and another one shared between instances of ChildB.

Is it right?

Well, I think it is not considered good. One of the related discussions to this is in comments to the following SO question and also under my answer to the question:

How to do "static overloaded const" in C#?

like image 67
Ozair Kafray Avatar answered Dec 29 '22 01:12

Ozair Kafray