Search code examples
c++classvirtual

virtual class in abstract class


Hello :) i would like to ask, if it's posible to make something like this:

i have base class (parent) A and three other classes (childs) B C D in class A, i have virtual functions, that's ok. but what if i need a virtual class ?

class A 
{
public:
    virtual int func1()=0;
    virtual int func2()=0;

    virtual class AB; // !!!!???
};

class B
{
public:
    int func1();
    int func2();

    class AB
    {
    public:
    ....
    };
};

classes B C D are same as class B. Now, i would like to create class instance and it should automaticly "redirect" class to instance of B or C D etc like functions.

is it possible ? i hope, you understand :) Thank you very much for answer.


Solution

  • This is fundamentally impossible. A virtual function call is determined at runtime. A class changes the behaviour of the program at compile-time. You can't make a compile-time determination at runtime unless runtime and compiletime are the same time, i.e. using a JIT or other dynamic code generators. In standard C++, this is impossible.

    What you CAN do is have a base class AB, with a virtual function that creates a class that is guaranteed to inherit from this base class, and then return a pointer to that.