how to find object type of derived class on Runtime

Apr 25, 2017 at 10:01am
I have following code

class Base() {

};


class Derived1: public Base {

};

class Derived1: public Base {

};

class Derived2: public Base {

};
class Derived3: public Base {

};
class Derived4: public Base {

};


void f(Base b) {

}

int main() {

Base arrayB[10];

arrayB can have objects of Derived classes also
}




Now I want to implement a function

void f (Base b) {

}


for derived class Derived 4 I have to implement a special function for rest of the objects of arrayB I have to implement other code one common functionality

I do not want to write the following code

void f(B* b) {
if (b->typeId() == Derived4) {
} else {

}
}



Is there any was we class object can be recognized on runtime


Apr 25, 2017 at 10:30am
arrayB can have objects of Derived classes also
No. Pointer is required.

For the pointer you can access derived objects with dynamic_cast:

http://en.cppreference.com/w/cpp/language/dynamic_cast
Apr 25, 2017 at 12:05pm
No my question is is there any way I write two versions of function f

void f(B* b) {
}

void f(Derived4 *d) {

}

int main() {

Base arrayB[10];
for(int i =0 ; i < 10; i++) {
f(arrayB[i]);
}


now this is just an example we can have 100s of objects as Derived4 where we need to have special handling in f


Could you please let me know can we use templates in such cases



Apr 25, 2017 at 1:09pm
No my question is is there any way I write two versions of function f
Yes, no problem. Which function is called depends on the type provided. The function will not check whether a provided B * could be Derived4 *. This is up to you.
Apr 25, 2017 at 2:21pm
if we have 100 versions of Derivedn which has to be specially handled and what should be done. what is bet optimized code
Apr 26, 2017 at 6:22am
Well, 100 version doesn't sound like a reasonable design...

However, depending on what you are trying to accomplish virtual functions might be what you're looking for:

http://www.cplusplus.com/doc/tutorial/polymorphism/

A virtual member is a member function that can be redefined in a derived class, [...]


Could you please let me know can we use templates in such cases
A template might avoid hundreds of derived class. it depends on what you are trying to do.
Topic archived. No new replies allowed.