devxlogo

Menus Using Virtual Functions

Menus Using Virtual Functions

Question:
What is giving me a redefinition of CMenuItems class error in this code?

//cmenu.hclass CMenuItem {   public:      char title[81];      virtual void Do_Command(void)=0;};//*********************//CMDS.CPP Defines and initializes menu commands.#include #include #include "cmenu.h"class CMenuBell:public CMenuItem{   void Do_Command(void);};class CMenuSaying:public CMenuItem{   void Do_Command(void);};class CMenuAdd:public CMenuItem{   void Do_Command(void);};void CMenuBell::Do_Command(void){   putc('07',stdout); // "07" rings a bell}void CMenuSaying::Do_Command(void){   puts("If you know the meaning of the universe,");   puts("Make the sound of one hand clapping.");}void CMenuAdd::Do_Command(void){   double x,y;   printf("Enter a number: ");   scanf("%lf",&x);   printf("Enter a number: ");   scanf("%lf",&y);   printf("The total is %f.", x+y);}int num_commands;CMenuItem *commands[20];void Init_Commands(void) {   commands[0] = new CMenuBell;   strcpy(commands[0]->title, "Sound a bell.");   commands[1] = new CMenuSaying;   strcpy(commands[1]->title, "Print a message.");   commands[2] = new CMenuAdd;   strcpy(commands[2]->title, "Add two numbers.");   num_commands=3;}//************************//Main.cpp#include #include "cmenu.h"#include "CMDS.cpp"extern int num_commands;extern CMenuItem *commands[];void main(void) {   int i, sel;   Init_Commands();   do {      puts("
MENU:
");      for (i=0; ititle");      printf("
Enter a selection: ");      scanf("%d", &sel);      if (sel>0 && sel<=num_commands)         commands[sel]->Do_Command();   } while (sel <= num_commands);}

Answer:
The problem is that you're #including the header "cmenu.h" twice:

 //CMDS.CPP Defines and initializes menu commands. #include  #include  #include "cmenu.h" // first time   //Main.cpp #include  #include "cmenu.h" // second time #include "CMDS.cpp"

To avoid this, you should add #include guards in "cmenu.h". This will prevent the multiple definition problem:

 #ifndef CMENU_H #define CMENU_H //cmenu.h class CMenuItem {    public:   char title[81];   virtual void Do_Command(void)=0; }; #endif

It's always a good idea to add #include guards to every header file you write.

devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist