Search code examples
c++visual-c++inheritanceconstructorinitializer-list

no appropriate default constructor available error with initializer list


For some reason I'm getting the no default constructor error even though I'm using a member initializer. What am I doing wrong?

A minimal example,

a.cpp

#include "a.h"


a::a(int x, int y, int z):x(x),y(y),z(z)
{
}

a.h

class a
{
public:
    a(int x, int y, int z);

private:
    int x, y, z;
};

b.cpp

#include "b.h"


b::b()
    :ao(1,2,3)
{
}

b.h

#include "a.h"

class b: public a
{
public:
    b();

private:
    a ao;
};

Solution

  • Your b has two a objects in it: one is called ao and is a member variable, and the other is the one b is inherited from. You're already initializing ao explicitly in the initializer list, but you're not initializing b's parent. You can do this by inserting a(4,5,6), in the initializer list immediately before ao(1,2,3).