Home > Software engineering >  Undefined reference to a virtual function
Undefined reference to a virtual function

Time:12-31

booking.h

#ifndef _BOOKING_H_
#define _BOOKING_H_

#include <string>

class Event {
  private:
   std::string event_option;
  public:
   Event(std::string event_option);
   virtual ~Event();
   void list_specific_event_details();
   virtual void list_details();
};

class Films : public Event {
 private:
  std::string movie_option;
 public:
  Films(std::string movie_option);
  void list_details();
};

class Live_Music : public Event {
 private:
  std::string live_music_option;
 public:
  Live_Music(std::string live_music_option);
  void list_details();
};

class Standup_Comedy : public Event {
 private:
  std::string comedy_option;
 public:
  Standup_Comedy(std::string comedy_option);
  void list_details();
};
#endif

booking.cpp

#include "booking.h"
#include <string>
Event::Event(std::string event_option)
{
  this->event_option = event_option;

}

Event::~Event()
{
}


void Event::list_specific_event_details()
{
  return list_details();
}


Films::Films(std::string movie_option) : Event("Films")
{
  this->movie_option = movie_option;

}

void Films::list_details()
{
    //some code ...

    return;

}

Live_Music::Live_Music(std::string live_music_option) : Event("Live_Music")
{
  this->live_music_option = live_music_option;

}

void Live_Music::list_details()
{

    //some code...

  return;

}

Standup_Comedy::Standup_Comedy(std::string comedy_option) : Event("Standup_Comedy")
{
  this->comedy_option = comedy_option;

}

void Standup_Comedy::list_details()
{
    //some code...
  return;

}

main.cpp

#include "booking.h"
#include <iostream>
#include <vector>
#include <string>

int main()
{
  std::vector <Event *> choice;
  choice.push_back(new Films("f"));
  choice.push_back(new Live_Music("l"));
  choice.push_back(new Standup_Comedy("s"));

  for(unsigned i = 0; i < choice.size(); i  )
    {
      choice[i] -> list_specific_event_details();
    }


  for (Event * e: choice) delete e;
  choice.clear();

}

I have written the above block of codes and got an error when I tried to compile it.

The error is as follows:

/usr/lib/gcc/x86_64-pc-cygwin/11/../../../../x86_64-pc-cygwin/bin/ld: /tmp/ccuWXzBM.o:booking.cpp:(.rdata$_ZTV5Event[_ZTV5Event] 0x20): undefined reference to `Event::list_details()' collect2: error: ld returned 1 exit status

Why am I getting this error and how can I solve it?

Thankful for any help that can be offered.

CodePudding user response:

You have not defined your method Event::list_details(). If you only want to declare the function but do not want to implement it, that is what is called an Interface, you can make it a pure virtual method with:

class Event
{
...
    virtual void list_details() = 0;`
...
};
  • Related