Search code examples
c++undefined-referenceundefined-symbol

Undefined symbol when defined outside class, works when defined inside class


I'm somewhat new to C++ and am trying to understand the syntax and its behaviour. In particular, after quite a bit of googling and research, I was unable to find out why the following code won't compile:

class base {
public:
    base (const int);
};

class child: base {
public:
    child (const int);
};

child::child(const int num) : base(num) {}

but this will:

class base {
public:
    base (const int);
};

class child : base {
public:
    child (const int num) : base(num) {};
};

In the above case the linker fails with:

Undefined symbol base::base(int)

I feel like I'm making a very stupid mistake but the compiler's errors are completely unhelpful.


Solution

  • The compiler is telling you exactly what the problem is. You must define a constuctor for base if you invoke it, and you are invoking it from the derived class child.

    Try adding this to your code:

    base::base(const int num) {}
    

    This ignores the given argument, but at least your code will compile.

    I would probably remove the declaration for the base constructor and not pass any value to it from the child class unless it was actually used.

    In the second case, the constructor is inline and never invoked so the compiler does not need to generate code for it, but if you try to actually construct a child object, you will get the same linker error.

    The reason inline code is not generated is because you have no invoking call site. The whole purpose behind declaring code inline is so that it is inlined at the call site. Thus the compiler defers code generation for all inline code until it is actually called.