Click here to Skip to main content
15,916,527 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Suppose I have a base class named Base and there is a function in Base named Reset, I am going to define array of Base class but every time I want to reset all array items I have to iterate all elements Reset function.

My question is : Is there a way I derive the Base class as Child class which consists of array of Base and create a ResetAll function in Child to iterate all Reset functions of the array?

Or maybe create a ResetAll function which will trigger all Reset functions?

What I have tried:

It's just concept question so practically i just created the class and array but couldn't manage to derive a child which is array of base and is able to reset all items.
Posted
Updated 20-Jul-18 23:41pm
v6

1 solution

No. C does not support classes at all, so there is no way to create a Base class in the first place.

If you are talking about C++ or C# instead (and if you are, then tagging your question appropriately helps a lot) then yes, you can.

One way I do things is to have the Base class contain a static collection of it's instances (C# code here):
public class Base
    {
    private static List<Base> all = new List<Base>();
    private Base()
        {
        all.Add(this);
        }
    public static Base Create()
        {
        return new Base();
        }
    public static Base[] GetAll()
        {
        return all.ToArray();
        }
    }
It would be easy to add the Reset and ResetAll methods to that:
public virtual void Reset()
    {
    ...
    }
public static void ResetAll()
    {
    foreach (Base b in all)
        {
        b.Reset();
        }
    }
You can do similar things in C++.
 
Share this answer
 

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