A
A
Alexey2013-12-27 13:26:24
OOP
Alexey, 2013-12-27 13:26:24

About inheritance in OOP. How can I get the name of a derived class from a base class?

Good afternoon!
There is a base class and n-th number of derivatives. The base class is abstract (but that doesn't matter) while providing a non-virtual function.

class Base()
{
    ...
    void f();
    ...
}

class Der1(): public Base
{ ... }
class Der2(): public Base
{ ... }

Interaction with derived classes occurs through a pointer to the base class:
Base* base = new Der1;
base->f();

In this scenario, is there any way to catch which base class (preferably the class name in string form) called the f() function?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
T
Trrrrr, 2013-12-27
@Renzo

If it's C++, then there is no good option.
You can use dynamic_cast to cast back a type or a typeid ( msdn.microsoft.com/en-us/library/fyf39xec.aspx ).
As for me, the best option is to fence your virtual functions that need to be redefined.
And what kind of task, where is this needed?
In the overwhelming majority of cases, if this is necessary, then this indicates a flawed program architecture, most likely the task can be solved much more elegantly without resorting to such nonsense.

O
OnYourLips, 2013-12-27
@OnYourLips

About inheritance in OOP (find the name of a derived class from a base class)

In OOP, this cannot be done, because violates the principle of dependency inversion in OOP. And it won't be OOP.

T
tsarevfs, 2013-12-27
@tsarevfs

If you can't just add a virtual function, you can try getting information about the type using typeid . It is suspicious that such a task arose.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question