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.

devx-admin

devx-admin

Share the Post:
2D Semiconductor Revolution

Disrupting Electronics with 2D Semiconductors

The rapid development in electronic devices has created an increasing demand for advanced semiconductors. While silicon has traditionally been the go-to material for such applications,

Cisco Growth

Cisco Cuts Jobs To Optimize Growth

Tech giant Cisco Systems Inc. recently unveiled plans to reduce its workforce in two Californian cities, with the goal of optimizing the company’s cost structure.

FAA Authorization

FAA Approves Drone Deliveries

In a significant development for the US drone industry, drone delivery company Zipline has gained Federal Aviation Administration (FAA) authorization, permitting them to operate drones

Mortgage Rate Challenges

Prop-Tech Firms Face Mortgage Rate Challenges

The surge in mortgage rates and a subsequent decrease in home buying have presented challenges for prop-tech firms like Divvy Homes, a rent-to-own start-up company.

Lighthouse Updates

Microsoft 365 Lighthouse: Powerful Updates

Microsoft has introduced a new update to Microsoft 365 Lighthouse, which includes support for alerts and notifications. This update is designed to give Managed Service

Website Lock

Mysterious Website Blockage Sparks Concern

Recently, visitors of a well-known resource website encountered a message blocking their access, resulting in disappointment and frustration among its users. While the reason for

2D Semiconductor Revolution

Disrupting Electronics with 2D Semiconductors

The rapid development in electronic devices has created an increasing demand for advanced semiconductors. While silicon has traditionally been the go-to material for such applications, it suffers from certain limitations.

Cisco Growth

Cisco Cuts Jobs To Optimize Growth

Tech giant Cisco Systems Inc. recently unveiled plans to reduce its workforce in two Californian cities, with the goal of optimizing the company’s cost structure. The company has decided to

FAA Authorization

FAA Approves Drone Deliveries

In a significant development for the US drone industry, drone delivery company Zipline has gained Federal Aviation Administration (FAA) authorization, permitting them to operate drones beyond the visual line of

Mortgage Rate Challenges

Prop-Tech Firms Face Mortgage Rate Challenges

The surge in mortgage rates and a subsequent decrease in home buying have presented challenges for prop-tech firms like Divvy Homes, a rent-to-own start-up company. With a previous valuation of

Lighthouse Updates

Microsoft 365 Lighthouse: Powerful Updates

Microsoft has introduced a new update to Microsoft 365 Lighthouse, which includes support for alerts and notifications. This update is designed to give Managed Service Providers (MSPs) increased control and

Website Lock

Mysterious Website Blockage Sparks Concern

Recently, visitors of a well-known resource website encountered a message blocking their access, resulting in disappointment and frustration among its users. While the reason for this limitation remains uncertain, specialists

AI Tool

Unleashing AI Power with Microsoft 365 Copilot

Microsoft has recently unveiled the initial list of Australian clients who will benefit from Microsoft 365 (M365) Copilot through the exclusive invitation-only global Early Access Program. Prominent organizations participating in

Microsoft Egnyte Collaboration

Microsoft and Egnyte Collaboration

Microsoft has revealed a collaboration with Egnyte, a prominent platform for content cooperation and governance, with the goal of improving real-time collaboration features within Microsoft 365 and Microsoft Teams. This

Best Laptops

Top Programming Laptops of 2023

In 2023, many developers prioritize finding the best laptop for programming, whether at home, in the workplace, or on the go. A high-performing, portable, and user-friendly laptop could significantly influence

Renaissance Gaming Magic

AI Unleashes A Gaming Renaissance

In recent times, artificial intelligence has achieved remarkable progress, with resources like ChatGPT becoming more sophisticated and readily available. Pietro Schirano, the design lead at Brex, has explored the capabilities

New Apple Watch

The New Apple Watch Ultra 2 is Awesome

Apple is making waves in the smartwatch market with the introduction of the highly anticipated Apple Watch Ultra 2. This revolutionary device promises exceptional performance, robust design, and a myriad

Truth Unveiling

Unveiling Truths in Bowen’s SMR Controversy

Tony Wood from the Grattan Institute has voiced his concerns over Climate and Energy Minister Chris Bowen’s critique of the Coalition’s support for small modular nuclear reactors (SMRs). Wood points

Avoiding Crisis

Racing to Defy Looming Financial Crisis

Chinese property developer Country Garden is facing a liquidity challenge as it approaches a deadline to pay $15 million in interest associated with an offshore bond. With a 30-day grace

Open-Source Development

Open-Source Software Development is King

The increasingly digital world has led to the emergence of open-source software as a critical factor in modern software development, with more than 70% of the infrastructure, products, and services

Home Savings

Sensational Savings on Smart Home Security

For a limited time only, Amazon is offering massive discounts on a variety of intelligent home devices, including products from its Ring security range. Running until October 2 or while

Apple Unleashed

A Deep Dive into the iPhone 15 Pro Max

Apple recently unveiled its groundbreaking iPhone 15 Pro and iPhone 15 Pro Max models, featuring a revolutionary design, extraordinary display technology, and unrivaled performance. These new models are the first

Renewable Crypto Miners

Crypto Miners Embrace Renewable Energy?

As the cryptocurrency sector deals with the fallout from the FTX and Celsius exchange collapses, Bitcoin miners are increasingly exploring alternative energy sources to reduce expenses and maintain profitability. Specialists

Laptop Savings

The HP Omen 16 is a Gamer’s Dream

Best Buy is currently offering an unbeatable deal on the HP Omen 16 gaming laptop, giving potential buyers the chance to save a significant $720 on their purchase. Originally priced

How to Check for Vulnerabilities in Exchange Server

It is imperative to keep your systems and infrastructure up-to-date to mitigate security issues and loopholes, and to protect them against any known vulnerabilities and security risks. There are many

Data Center Creation

Transforming Corporate Campuses into Thriving Data Centers

Dallas-based developer Compass Datacenters has purchased a 197-acre ex-corporate campus in Hoffman Estates, Illinois for an estimated $194 million. This acquisition occurs as more companies are downsizing and consolidating their

Nano Unbeatable Value

Lenovo ThinkPad X1 Nano: Unbeatable Value

The Lenovo ThinkPad X1 Nano, a first-generation model beloved for its ergonomic keyboards and stylish appearance, is now available at an unbeatable price of $600 on eBay. Though this 13-inch

Assistant Revolution

Home Assistant Green Makes Your Home Futuristic

In recent times, the growing interest in smart home technology has led to the emergence of various devices and platforms that enable homeowners to control and manage their homes in

Ultimate Smart Home

Unlock Your Ultimate Smart Home Adventure

Ever thought about having a home where everything is tailored to your needs and runs smoothly? Home automation may significantly impact your daily life. Transform your space into an intelligent

Gaming Laptops

Lenovo Legion Laptops Revolutionize Gaming

The gaming laptop market has recently been graced with two potent contenders, the Lenovo Legion 9i and the Legion Pro 7i. Both laptops boast powerful 13th-gen Intel Core i9 processors

Fintech Revolution Leap

Figure’s Bold Leap Beyond Banking

Figure, a fast-growing fintech startup, recently retracted its bid to become a bank, sparking speculation that the process was too challenging. However, the true reason behind Figure’s decision was its