0

I am currently a beginner at Object Orientated Programming. I am practicing inheritance and abstraction with base and derived classes using both header and cpp files. However, i am continually getting the following error.

main-1-1.cpp:(.text+0x2b): undefined reference to `Derived::Derived()'
clang: error: linker command failed with exit code 1 (use -v to see invocation)

I cannot seem to work out why. I have attempted to swap/rearrange the destructor and constructors throughout the cpp and header files but it still shows the same error.

Any help would be much appreciated! The code is as follows:

Base.h:

#ifndef BASE_H
#define BASE_H

class Base {
 public:
  virtual void print() = 0;
  Base();
  virtual ~Base();
};

#endif /* BASE_H */

Base.cpp

#include "Base.h"

#include <iostream>
using namespace std;

Base::Base() { cout << "\n Constructor Base class"; }
Base::~Base() { cout << "base destructor called"; }

main.cpp

#include "Base.h"
#include "Derived.h"

int main() {
  Base *bptr = new Derived;  // A pointer object reference the Base class.
  bptr->print();
  delete bptr;  // Delete the pointer object.
}

Derived.h:

#ifndef DERIVED_H
#define DERIVED_H

#include "Base.h"

class Derived : public Base {
 public:
  Derived();
  void print();
  ~Derived();
};

#endif /* DERIVED_H */

Derived.cpp:

#include "Derived.h"
#include "Base.h"

using namespace std;
#include <iostream>
Derived::Derived() { cout << "\n Constructor Derived class"; }
void Derived::print() { cout << "Derived is printing." << endl; }
Derived::~Derived() { cout << "Derived class Destructor" << endl; }
Evg
  • 25,259
  • 5
  • 41
  • 83
Luke
  • 1
  • 2
    You did not compile and link the `Derived.cpp` file properly. Add the `Derived.cpp` file to the list of files to compile and link in the same way that `main.cpp` and `Base.cpp` should have been added. – user17732522 Oct 21 '22 at 01:32
  • 1
    Code looks OK but what is your compile command? – GAVD Oct 21 '22 at 01:34

0 Answers0