Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return a function from multiple derived classes

I have a base class and multiple derived classes from it. Each derived class has a constructor that accepts parameters that were initialized in the base class. All of the constructors are different, however they all accept one common parameter, let's call it Name.

Is there a way for me to display every derived class' name in a shorter way than calling them one after another?

Here's an example. Let's say my base class is Father and my derived classes are Brother, Sister, HalfBrother, HalfSister and this is my driver file:

cout << Brother::Brother().getName() << endl
     << Sister::Sister().getNAme() << endl
     << HalfBrother::HalfBrother().getNAme() << endl
     << HalfSister::HalfSister().getName() << endl;

This will return them fine, but is there a simpler way to do this so that I can get all the names from all the derived classes without having to write them one by one?

like image 243
jsan Avatar asked Mar 24 '26 21:03

jsan


1 Answers

You can create a static registry of classes, and populate it from constructors of static members that you insert into classes that you would like to register.

In the header:

class Registration {
    static vector<string> registered;
public:
    static void showRegistered() {
        for (int i = 0 ; i != registered.size() ; i++) {
            cout << registered[i] << endl;
        }
    }
    Registration(string name) {
        registered.push_back(name);
    }
};

In the CPP file:

vector<string> Registration::registered;

With this class in hand, you can do this:

In the headers:

class A {
    static Registration _registration;
};

class B {
    static Registration _registration;    
};

class C {
    static Registration _registration;    
};

In the CPP files:

Registration A::_registration("quick");
Registration B::_registration("brown");
Registration C::_registration("fox");

This last part is key: declarations of the static _registration variables have a side effect - they insert the name into the vector<string> registered of the Registration class, in no specific order. You can now retrieve the names, print them out, or do whatever you want with them. I added a member-function for printing, but obviously you are not limited by it.

Here is a demo on ideone - it prints

quick
brown
fox
like image 135
Sergey Kalinichenko Avatar answered Mar 26 '26 11:03

Sergey Kalinichenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!