1

I am getting compilation error. I am not able to figure it out whats the root cause.

I tried to comment on the constructor/desctructor of the Base class. And it worked. But uncommenting is causing a compilation error.

#include<iostream>
using namespace std;

class BaseException{
    public:
        BaseException();
        virtual ~BaseException();
        virtual void dumpmsg() = 0;

};

class DerivedException : public BaseException
{
    public:
        DerivedException():BaseException()
        {   
        }
        void dumpmsg() override
        {
            std::cout<< "Child class exception cuaght" << std::endl;
        }   
};
void h()
{
    throw  ( DerivedException() );
}
void g()
{
    h();
}
void f()
{
    g();
}
int main()
{
    try{
        f();
    }
    catch( BaseException &ex )
    {
        ex.dumpmsg();
    }
}

Error Msg:

In function `ZN16DerivedExceptionC1Ev`:
15 `undefined reference to BaseException::BaseException()`
In function `ZN16DerivedExceptionD1Ev`:
12 `undefined reference to BaseException::~BaseException()`
[Error] ld returned 1 exit status
lubgr
  • 37,368
  • 3
  • 66
  • 117
am an
  • 41
  • 3
  • 3
    The linker is saying you haven't defined (implemented) the `BaseException` constructor and destructor. Where do you define (implement) them? I can only see their declarations. – Some programmer dude Jul 22 '19 at 06:55
  • They are linker errors, not compilation errors. The constructor and destructor of `BaseException` are both declared but not defined. – Peter Jul 22 '19 at 07:06
  • Possible duplicate of [What is an undefined reference/unresolved external symbol error and how do I fix it?](https://stackoverflow.com/questions/12573816/what-is-an-undefined-reference-unresolved-external-symbol-error-and-how-do-i-fix) – Alan Birtles Jul 22 '19 at 08:14

1 Answers1

3

You declare both default constructor and virtual destructor for the class BaseException, but you don't provide any definition. You need to add

BaseException() = default;
virtual ~BaseException() = default;

or, if the default behavior isn't sufficient for your needs, a function body. Note that virtual void dumpmsg() = 0; is different here. It's not a special member function, and it's pure (= 0), which allows the linker to do its work without a definition for BaseException::dumpmsg().

lubgr
  • 37,368
  • 3
  • 66
  • 117