Why calling pure virtual function imlemented in child inside constructor doesn't work?

StackOverflow https://stackoverflow.com/questions/23452383

  •  15-07-2023
  •  | 
  •  

Pergunta

I am trying to understand why, and if it is possible to call child method from parent constructor.

First I tried:

#define prn printf(__FUNCTION__);printf("\r\n");

class A
{
public:
    A(){init();}
     ~A(){prn;}

     virtual void f(){}

     virtual void init()=0;
};

class B : public A<B>
{
public:
    B(){prn;}
    ~B(){prn;}

    virtual void init(){prn;}
};

Which crushed with pure virtual call. I can guess its because init() in A() points to init() in A's virtual table. With this line I confirmed it:

virtual void init()=0{prn};

So, I tried the following:

template<typename T>
class A
{
public:
    A(){((T*)this)->init();}
     ~A(){prn;}

     virtual void f(){}

     virtual void init()=0{prn;}
};

class B : public A<B>
{
public:
    B(){prn;}
    ~B(){prn;}

    virtual void init(){prn;}
};

Which also crushed! Now my only guess is that it happens because the virtual table is just being made, but its just a guess...

Can anyone explain what is going on?

Thanks!

Foi útil?

Solução

When you are in the base class constructor, the details of the derived class has not been filled in yet -- which means the virtual function table is not completely filled in yet. The virtual function table does not point to any of the derived class functions.

If you call a virtual member function from the base class constructor, several things can happen:

  1. If the base class has an implementation of the function, that will be called. This will be the best case scenario. Remember that it is possible to define a virtual member function in the base class even if it is declared pure virtual.

  2. If the base class does not have a member function, the entry in the virtual function table for the function could be NULL (well initialized) or something uninitialized. You are likely to get an exception thrown or segmentation violation, or any behavior -- you are entering the territory of undefined behavior.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top