"undefined reference to `____: :___`" error for pure virtual functions when I seperate my files into cpp and header files

Viewed 40

So I have the Book class that inherits from Publication.

Publication has two pure virtual functions which I implemented in Book.

The code worked before I tried seperating into header and cpp files

classes.h

#include <iostream>
#include <string>
using namespace std;

class Publication
{
protected:
  // Common attributes
  string title;
  float price;

public:
  // Two pure virtual functions that will need implementation in derived classes
  virtual void getData() = 0;
  virtual void putData() = 0;

};


class Book : public Publication 
{
private:
  int pages;

public:
  void getData();
  void putData();

};

classes.cpp

#include "classes.h"
// getData implementation - gets inputs from user
void Book::getData () {
  cout << "Enter title: ";
  cin >> title;
  cout << "Enter price: ";
  cin >> price;
  cout << "Enter number of pages: ";
  cin >> pages;
  cout << endl;

}

// putData implementation - prints out Book info
void Book::putData() {
  cout << "Title: " << title << endl;
  cout << "Price: " << price << endl;
  cout << "Pages: " << pages << endl;

}

main.cpp

#include <iostream>
#include <string>
#include "classes.h"
using namespace std;


int main() {
  Book book1;

  book1.getData();

  book1.putData();
  

  return 0;
}

This is one of the errors

: undefined reference to Book::getData()'

but it says it for the putData function as well

1 Answers

I realized I was just dumb and forgot that I need to compile both cpp files and not just main.cpp

Running g++ main.cpp task1.cpp caused no errors.

Related