Home > Back-end >  C Base class initialize with member of derived class gives warning "uninitialized field"
C Base class initialize with member of derived class gives warning "uninitialized field"

Time:12-01

I use a base class (A) that manages some data but without having the storage. The derived class (B) has a storage member and initializes the base class (A) with a pointer to that storage and the size of them.

The code model (clang) in the IDE gives me a warning "Field mStorage is uninitialized when used here" at line explicit B() : A(mStorage.data(), 10) {}

Question 1: Is this a problem as long as I do not use the storage in the base class constructor?

Question 2: If this doesn't cause a problem, is there a way to avoid this warning?

class A
{
public:
    explicit A(int* p, size_t s)
        : mPtr(p), mSize(s)
    {}

    void append(int i) { /* ... */ }

private:
    int*   mPtr  = nullptr;
    size_t mSize = 0;
};


template <size_t N>
class B : public A
{
public:
    explicit B() : A(mStorage.data(), N) {}

private:
    std::array<int, N> mStorage {};
};

Update:

  • add template <size_t N> to class B
  • My intension is to decouple the normal usage of the class and the template size in class B
void worker_function(const A& a)
{
    a.append(int(1));
}

// and also

struct Foo
{
    Foo(const A& a) : m_a(a) {}

    void do_some_work()
    {
         a.append(int(1));
    }

    const A& m_a;
}; 

void main()
{
    B<10> b;
    worker_function(b);
    // and also
    Foo foo(b);
    foo.do_some_work();
}

CodePudding user response:

This might work as you intend, but compiler warnings should not be ignored. mStorage doesn't exist yet at the time A is constructed. The base class is constructed first. Maybe the compiler, looking at mStorage, will peek ahead, so to speak, but that's not the required sequence. mStorage is probably just random garbage.

From the skeleton, it's hard to guess what the intent is, but you could easily solve the problem by making a virtual function that returns a pointer to the storage in the derived class. You may also find some sort of template solution.

I suggest you tell us a little more about why you want to design a class this way.

UPDATE: C is unhappy not knowing what N is for a good reason. What happens when worker_function is called for the (N 1)st time?

  • Related