error C2440: 'initializing' : cannot convert from 'BaseMenu' to 'BaseMenu *' - c++

I am really hoping that you all can help me with this problem. I am both new to the site and new to C++ (only been learning for about a month). My compiler is VS2012. I am working on a set of menus for a program. The menus use simple switch statements for each of their classes. Each menu is derived from a base menu class. Since I do not seem to be having any issues with the menu classes themselves, I am not including them at the moment since they are all in separate .cpp files with their own .h header files. I am including the base menu .cpp and .h files since I believe they are part of my issue. I am also including my main .cpp file.
BaseMenu.h
#ifndef BaseMenu_M
#define BaseMenu_M
#include<string>
#include<iostream>
using std::cout;
class BaseMenu
{
public:
BaseMenu() { m_MenuText = "This is where the menu text choices will appear"; }// Constructor providing menu text to each derived menu
virtual ~BaseMenu() { } // virtual destructor
virtual BaseMenu getNextMenu(int iChoice, bool& iIsQuitOptionSelected); // used to set up the framework
virtual void printText() // member function to display the menu text
{
cout << m_MenuText << std::endl;
}
protected:
std::string m_MenuText; // string will be shared by all derived classes
};
#endif
BaseMenu.cpp
#include "stdafx.h"
#include "BaseMenu.h"
#include<iostream>
BaseMenu::BaseMenu(void)
{
}
BaseMenu::~BaseMenu(void)
{
}
Main .cpp file
#include "stdafx.h"
#include "BaseMenu.h"
#include "TicketSalesMenu.h"
#include "MainMenu.h"
#include "ListMenu.h"
#include "AdministrativeTasksMenu.h"
#include "basemenu.h"
#include <iostream>
#include <string>
using std::cin;
int tmain (int argc, _TCHAR* argv[])
{
BaseMenu* aCurrentMenu = new MainMenu; // Pointer to the current working menu
bool isQuitOptionSelected = false;
while (!isQuitOptionSelected) // set to keep menus running until the quit option is selected
{
aCurrentMenu->printText(); // call and print the menu text for the currently active menu
int choice = 0; // Initializing choice variable and setting it to 0
cin >> choice;
BaseMenu* aNewMenuPointer = aCurrentMenu->getNextMenu(choice, isQuitOptionSelected); // This will return a new object, of the type of the new menu we want. Also checks if quit was selected //**This is the line that the error is reported**//
if (aNewMenuPointer)
{
delete aCurrentMenu; // clean up the old menu
aCurrentMenu = aNewMenuPointer; // updating the 'current menu' with the new menu
}
}
return true;
}
For some reason I can not figure out, I am receiving a
error C2440: 'initializing' : cannot convert from 'BaseMenu' to 'BaseMenu*'. This error is in the main .cpp file on line 35, which is
"BaseMenu* aNewMenuPointer = aCurrentMenu->getNextMenu(choice, isQuitOptionSelected);"
I have looked at multiple similar questions from this site and others. One of the solutions I tried, resulted in multiple link errors for all my menu classes. It has taken me 3 days to get the errors reduced to just this one remaining error and I am at a loss.

The compiler is telling you the problem. getNextMenu returns an actual BaseMenu object, but you are trying to assign it to a pointer to a BaseMenu object.

Related

While seperating classes, using a function in cpp file causes errors

So i just learned how to seperate classes and the youtube totourial is stressing on doing this alot, here's the link
https://www.youtube.com/watch?v=NTip15BHVZc&list=PLAE85DE8440AA6B83&index=15
My code is the exact same as his, and in the cpp file theres this thing:
mainClass::myfunction; (mainclass is the name of my class, myfunction is my function)
when i try to execute my program, it gives an error:
unidentified reference to 'mainClass::myfunction()'
here's my main.cpp file code:
#include <iostream>
#include "mainclass.h"
using namespace std;
int main()
{
mainClass bo;
bo.myfunction();
return 0;
}
here's my mainclass.h code:
#ifndef MAINCLASS_H
#define MAINCLASS_H
class mainClass
{
public:
myfunction();
};
#endif // MAINCLASS_H
my mainclass.cpp:
#include "mainclass.h"
#include <iostream>
using namespace std;
mainClass::myfunction()
{
cout << "I am a banana" << endl;
}
I don't know much about these so could you just tell me what the errors here are, because i copied everything correctly from the guy's totourial but still it doesn't work
P.S: this happens to me alot, i understand everything, nothing works, i copy everything, nothing works, and then i literally do exactly what the person is doing, still nothing works on all three of PC's, so i dont think the problem is with the devices lol
I doubt you completely copied and pasted that code because I'm fairly sure a teacher shouldn't be teaching having functions without a specified return type, but let's jump into it anyways...
Possibility #1
You meant to create a constructor for the class. In that case, please make sure the constructor function has the same name as the class. Also, you can't call it through .mainClass(), as it is a constructor.
class mainClass
{
public:
mainClass();
};
mainClass::mainClass()
{
cout << "I am a banana" << endl;
}
Possibility #2 You meant to create the class member function myfunction. You really should be specifying what return type your function is of. Some compilers will auto-assume int return type, and so the function you created is int myfunction();, but you really should be specifying it as void myfunction(); since you didn't return anything. Addl. info: Does C++ allow default return types for functions?
Next, change how you are giving the definition, by adding the return type.
void mainClass::myfunction()
{
cout << "I am a banana" << endl;
}
Possibility #3 Those should work, but another issue is that you might not have linked mainclass.cpp, so there is no definition available. In code blocks, right click on the project name and hit Add Files, then add the mainclass.cpp so the linker can define mainClass::myfunction().
To troubleshoot if the mainclass.cpp is being built with the project, try adding
#error I'm included! to the file mainclass.cpp after #include "mainclass.h". If you get an error I'm included!, then it is linked and you can remove the #error.

C++ Hunter/Prey "C2027 undefined type" compilation error

I've been getting weird compile errors all over the place in a simple hunter/prey simulation (mostly because the professor hasn't explained the syntax for inherited classes and virtual functions very well) and I'm completely stuck on one issue. In this program, "Creatures" (an abstract class with "Hunter" and "Prey" children) walk around a "Grid" class in a Move(), Breed(), Die() cycle.
I'm getting the following errors: "C2027: use of undefined type 'Creature'" and "C2227: left of '->face' must point to class/struct/union/generic type" at the line specified in below (all my code's in the header because several students were getting unresolved externals in another project and the professor told us to just put it all in the headers). Let me know if I need to post more code.
I've gotten several other errors that I couldn't explain before this that seemed to be solved through a seemingly random combination of adding/removing included headers and pre-declaring classes, but an actual explanation of what's going wrong would be much appreciated so I'm not just flailing in the dark until it works. I understand the concept of what we're trying to do and even how to go about it for the most part, but as I mentioned, we didn't spend any time on the syntax of how to properly set up multiple files so that everyone works smoothly so any detailed explanation of how this should be done would be greatly appreciated.
Grid.h
#ifndef GRID_H
#define GRID_H
#include <iostream>
#include <cstdlib>
#include <cmath>
#include <ctime>
#include "Constants.h"
#include "creature.h"
using namespace std;
class Creature;
class Grid
{
public:
Creature* grid[MAX_X][MAX_Y];
Grid() //Initalizes the grid and spawns random creatures
{
for(int i = 0; i < MAX_X; i++)
for(int j = 0; j < MAX_Y; j++)
grid[i][j] = NULL;
}
void Move() //Tells each creature on the grid to move
{
//Call creature.Move() on each cell (if not NULL)
}
void Breed() //Tells each creature to breed (if it can)
{
//Call creature.Breed() on each cell (if not NULL)
}
void Kill() //Tells each creature to die (if it's old)
{
//Call creature.Die() on each cell (if not NULL)
}
char** Snapshot() //Creates a char array "snapshot" of the board
{
//Produces a 2D char array of the grid for display
}
Creature* Get(Coords here) //Returns a pointer to the object at the specified position
{
return grid[here.x][here.y];
}
char Occupant(Coords here) //Returns the character of the specified position
{
if(!Get(here))
return FACE_EMPTY;
Creature* temp = Get(here);
return temp->face; //*** ERRORS APPEAR HERE ***
}
void Clear(Coords here) //Deletes the object at the specified position
{
if(Get(here))
delete Get(here);
grid[here.x][here.y] = NULL;
}
};
#endif // GRID_H
creature.h
#ifndef CREATURE_H
#define CREATURE_H
#include <iostream>
#include <cstdlib>
#include <cmath>
#include <ctime>
#include "Constants.h"
#include "coords.h"
#include "grid.h"
using namespace std;
class Grid;
class Creature
{
public:
Grid* theGrid;
Coords position;
int stepBreed;
int stepHunger;
char face;
Creature(Grid* _grid, Coords _position, char _face) //Constructor
{
theGrid = _grid;
position = _position;
face = _face;
stepBreed = stepHunger = 0;
}
virtual Coords Move() = 0; //Allows the child to define it's own movement
virtual Coords Breed() = 0; //Allows the child to define it's own breeding
virtual bool Starve() = 0; //Allows the child to starve of its own accord
};
#endif // CREATURE_H
Your use of class Creature at the top of the file seems to indicate that you don't have access to the complete definition of Creature in this file. That makes it impossible for the compiler to do the -> operation on it - it doesn't know what the members of that class are! You need to have a complete definition of Creature in the same translation unit as this code. That is, Creature needs to be a complete type if you want to use it in this way.
Edit: Thanks for posting creature.h. Your problem (as mentioned in the comments below) is that you have a circular dependency problem. creature.h includes grid.h and vice versa. You'll need to break one of those links to get things working properly. In this case, removing #include "grid.h" from creature.h should do the trick - no code in creature.h depends on Grid being a complete type.

State Machines, Sub-Classes, and Function Pointers

I'm having trouble implementing a state machine for class. I keep getting the errors:
state.cpp:5: error: have0 was not declared in this scope
state.cpp:10: error: redefinition of State* Have0State::process(std::string)
state.h:18: error: virtual State* Have0State::process(std::string) previously defined here
I'm trying to get the Have0State to work before I continue onto the rest of the machine, hence the sparse code.
state.h:
#ifndef STATE_H
#define STATE_H
#include <string>
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <iostream>
class State{
public:
State(){};
virtual State* process(std::string input) = 0;
};
class Have0State: public State {
public:
Have0State():State(){};
virtual State* process(std::string input);
}have0;
#endif
state.cpp:
#include "state.h"
using namespace std;
State *currentState = &have0;
State* Have0State::process(string input){
if(input == "quarter"){
cout << "cool" << endl;
}
return &have0;
}
int main(int argc, char** argv) {
string input;
//get input
cin >> input;
while (input != "exit") {
currentState = currentState->process(input);
//get input
cin >> input;
}
return 0;
};
I've tried defining the process function as Have0State::State::process(string input) but that didn't work either. Any clarification on how function pointers are supposed to work, especially in the context of subclass member functions, I would greatly appreciate it.
EDIT: Also, what exactly is the have0 declaration at the end of the Have0State class declaration in the state.h file? It doesn't have an explicitly stated type; is it implied that it is of type Have0State??
There aren't any function pointers in your example. Also, like Marciej, I am able to compile (and run) this code.
But, since you asked, the 'have0' declaration simply declares an instance of the class. A class definition can be followed by 0 or more of these declarations (as well as initializers):
class Thing {...} one, another, many[3] = { Thing(1), Thing(2), Thing(3) };
the same as for any other type:
int counter = 0, flag = 0x80, limit = 500;
The possibility of this optional declarator list is why class, struct, union, and enum definitions must be followed with a semi-colon (to terminate the list).
But, as Karthik said, defining a variable in a header will cause "duplicate definition" errors at link time, if the header is included in more than one .cpp file. IMO it's fine though to use this technique to define and declare private objects in a .cpp file (rather than a .h file).

Multiple definition of the same symbol in C++ (visual studio)

I'm having an issue with a pretty simple code
I am following the tutorial of chrono::engine http://www.chronoengine.info/mediawiki/index.php/Demo_fourbar
I do not have much experience in C++ programming (I have some experience in Java), therefore I tried to define MyEventReceiver (a class from the tutorial) in a different file (MyEventReceiver.h and MyEventReceiver.cpp) to get my head around classic structure of a C++ code
Here is the version of the code
MyEventReceiver.h
#ifndef RECEIVER_H
#define RECEIVER_H
#include "physics/CHapidll.h"
#include "physics/CHsystem.h"
#include "irrlicht_interface/CHbodySceneNode.h"
#include "irrlicht_interface/CHbodySceneNodeTools.h"
#include "irrlicht_interface/CHdisplayTools.h"
#include "irrlicht_interface/CHirrWizard.h"
#include "core/CHrealtimeStep.h"
#include <irrlicht.h>
// Use the namespace of Chrono
using namespace chrono;
// Use the main namespaces of Irrlicht
using namespace irr;
using namespace core;
using namespace scene;
using namespace video;
using namespace io;
using namespace gui;
class MyEventReceiver : public IEventReceiver
{
public:
MyEventReceiver(ChSystem* asystem, IrrlichtDevice* adevice, ChSharedPtr<ChLinkEngine> aengine);
bool OnEvent(const SEvent& event);
void setText_enginespeed(IGUIStaticText* _text_enginespeed);
IGUIStaticText* getText_enginespeed();
private:
IGUIStaticText* text_enginespeed;
ChSystem* msystem;
IrrlichtDevice* mdevice;
ChSharedPtr<ChLinkEngine> mengine;
};
#endif
with the implementation as follows in MyEventReceiver.cpp
#include "MyEventReceiver.h"
// Constructor
MyEventReceiver::MyEventReceiver(ChSystem *asystem, IrrlichtDevice *adevice, ChSharedPtr<ChLinkEngine> aengine)
{
// store pointer to physical system & other stuff
// so we can tweak them by user keyboard
msystem = asystem;
mdevice = adevice;
mengine = aengine;
}
bool MyEventReceiver::OnEvent(const SEvent& event)
{
// check if user moved the sliders with mouse..
if (event.EventType == EET_GUI_EVENT)
{
s32 id = event.GUIEvent.Caller->getID();
IGUIEnvironment* env = mdevice->getGUIEnvironment();
switch(event.GUIEvent.EventType)
{
case EGET_SCROLL_BAR_CHANGED:
if (id == 101) // id of 'engine speed' gui
{
s32 pos = ((IGUIScrollBar*)event.GUIEvent.Caller)->getPos();
double newspeed = 10*(double)pos/100.0;
// set the speed into engine object
ChFunction_Const *spe_funct = dynamic_cast <ChFunction_Const*> (mengine->Get_spe_funct());
spe_funct->Set_yconst(newspeed);
// show speed as formatted text in interface screen
char message[50]; sprintf(message,"Engine speed: %g [rad/s]",newspeed);
text_enginespeed->setText(core::stringw(message).c_str());
}
break;
}
}
return false;
}
void MyEventReceiver::setText_enginespeed(IGUIStaticText* _text_enginespeed)
{
text_enginespeed = _text_enginespeed;
}
IGUIStaticText* MyEventReceiver::getText_enginespeed()
{
return text_enginespeed;
}
and the main file in Main_2.cpp (which I emptied, it gives me the same error with or without the code inside - which is basically only setting up the 3D engine Irrlicht and some mechanics features from the collision model of chrono::engine)
#include "MyEventReceiver.h"
int main()
{
return 0;
}
Basically the code defines an event receiver, so that the user after running the program can interact with the 3D environment built from the chrono::engine and Irrlicht engine through GUI manipulation
I define all the required libraries in the MyEventReceiver.h file and the required namespaces
The problem is that it does not compile (please note that I already tested the engines - with the same #include and using namespaces in just one file and it was working in a different project - ), i think the problem is coming from the structure of the header files
I got those lines of error
1>MyEventReceiver.obj : error LNK2005: "public: virtual bool __thiscall irr::scene::RTSCamera::OnEvent(struct irr::SEvent const &)" (?OnEvent#RTSCamera#scene#irr##UAE_NABUSEvent#3##Z) already defined in Main_2.obj
1>MyEventReceiver.obj : error LNK2005: "public: virtual void __thiscall irr::scene::RTSCamera::OnRegisterSceneNode(void)" (?OnRegisterSceneNode#RTSCamera#scene#irr##UAEXXZ) already defined in Main_2.obj
etc... (it goes on like this)
and the final mistake
1>C:\Users\****\Documents\Visual Studio 2010\Projects\TutorialChronoEngine\Debug\TutorialChronoEngine_2.exe : fatal error LNK1169: one or more multiply defined symbols found
I am using Visual Studio 2010 C++. I defined one global solution, and several projects in this very solution (the program I wrote above is one project among others)
I am sure it must be pretty easy to solve, but can't really find the solution. Let me know if you need further details
Thanks a lot
Best regards
Vincent
Edit : If I put all the codes in one single file as follows
#include "physics/CHapidll.h"
#include "physics/CHsystem.h"
#include "irrlicht_interface/CHbodySceneNode.h"
#include "irrlicht_interface/CHbodySceneNodeTools.h"
#include "irrlicht_interface/CHdisplayTools.h"
#include "irrlicht_interface/CHirrWizard.h"
#include <irrlicht.h>
// Use the namespace of Chrono
using namespace chrono;
// Use the main namespaces of Irrlicht
using namespace irr;
using namespace core;
using namespace scene;
using namespace video;
using namespace io;
using namespace gui;
// Get rid of the command windows that pops up when compiling and running
#ifdef _IRR_WINDOWS_
#pragma comment(linker, "/subsystem:windows /ENTRY:mainCRTStartup")
#endif
IGUIStaticText* text_enginespeed = 0;
class MyEventReceiver : public IEventReceiver
{
public:
MyEventReceiver(ChSystem* asystem,
IrrlichtDevice *adevice,
ChSharedPtr<ChLinkEngine> aengine)
{
// store pointer to physical system & other stuff
// so we can tweak them by user keyboard
msystem = asystem;
mdevice = adevice;
mengine = aengine;
}
bool OnEvent(const SEvent& event)
{
// check if user moved the sliders with mouse..
if (event.EventType == EET_GUI_EVENT)
{
s32 id = event.GUIEvent.Caller->getID();
IGUIEnvironment* env = mdevice->getGUIEnvironment();
switch(event.GUIEvent.EventType)
{
case EGET_SCROLL_BAR_CHANGED:
if (id == 101) // id of 'engine speed' gui
{
s32 pos = ((IGUIScrollBar*)event.GUIEvent.Caller)->getPos();
double newspeed = 10*(double)pos/100.0;
// set the speed into engine object
ChFunction_Const *spe_funct = dynamic_cast <ChFunction_Const*> (mengine->Get_spe_funct());
spe_funct->Set_yconst(newspeed);
// show speed as formatted text in interface screen
char message[50]; sprintf(message,"Engine speed: %g [rad/s]",newspeed);
text_enginespeed->setText(core::stringw(message).c_str());
}
break;
}
}
return false;
}
private:
ChSystem* msystem;
IrrlichtDevice* mdevice;
ChSharedPtr<ChLinkEngine> mengine;
};
int main(int argc, char* argv[])
{
return 0;
}
In that way, I avoid defining several times functions from the Irrlicht 3D engine that are not defined as inline. Unfortunately, this way of coding can become really cumbersome if a project becomes big (having to define all classes that rely on the 3D engine in one unique .cpp file), is there a design pattern to follow so that it is possible to avoid multiple defined objects with each class defined in a separate file ?
Thanks a lot
Best
Vincent
The linker is complaining about two of your functions being defined multiple times. As you could probably figure out from the errors, these functions are:
irr::scene::RTSCamera::OnEvent(struct irr::SEvent const &)
irr::scene::RTSCamera::OnRegisterSceneNode(void)
What's most likely happening here is that these two functions are defined in a header file, but:
Their definition does not appear directly in the class definition (so they are not implicitly declared to be inline);
Their out-of-class definition in the header file is not explicitly marked as inline.
As a result, if the header is included multiple times in different translation units (i.e. in different .cpp files), multiple definitions of the same functions will end up being present in the object code of those translation units.
When merging them, the linker will complain that you are breaking the ODR (One Definition Rule).

Parameters File to Store All Variables

Background: So I've created an application that is basically a large preference dialog where the user can configure a number of pages, each with a bunch of different settings. These settings are in the form of dropdowns and text boxes. I want to store all of the variables into one massive "Parameters.h" file so that I can access them from anywhere in my application. Each sub-page has it's own source and header file.
I'm having trouble with the pointers though. I'm not sure how to reference the Parameters class. Basically, my application has two main components: a main dialog and a bunch of sub, child pages. The main dialog is where the sub-pages are shown and hidden, based on what page the user chooses in a listbox on the left of the main dialog.
I'm just working with one sub-page right now, and have the following, but when I debug, I'm getting <BadPtr> all over the place. I have greatly simplified the code, but it should be enough to figure out what I'm doing wrong.
Question: So how do I point to this Parameters class in each sub-dialog so that I can store and use all of these variables?
SAPrefsDialog.cpp: Main dialog that houses the sub-pages
BOOL CSAPrefsDialog::OnInitDialog()
{
CDialog::OnInitDialog();
FSC_Main fscMain;
fscMain.SetParametersPointer(&m_pParams);
// [ ... ]
}
SAPrefsDialog.h: Main dialog header file
#include "Parameters.h"
public:
CSAPrefsDialog(CWnd* pParent = NULL); // standard constructor
~CSAPrefsDialog();
Parameters m_pParams;
FSC_Main.h: Sub-page header file
#include "Parameters.h"
class FSC_Main : public CSAPrefsSubDlg
{
// Construction
public:
FSC_Main(CWnd* pParent = NULL); // standard constructor
// Dialog Data
//{{AFX_DATA(FSC_Main)
enum { IDD = IDD_FS_CONFIG_MAIN };
//}}AFX_DATA
public:
void SetParametersPointer(Parameters* pParameters)
{ m_Params = pParameters; }
private:
Parameters *m_Params;
};
Parameters.h
#include "stdafx.h"
#include "prefs.h"
#pragma once
class Parameters
{
public:
Parameters(); // standard constructor
public:
~Parameters(void);
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
public:
//*****************************************************************************
//
// FSC_Main.cpp Variables
//
//*****************************************************************************
CString m_strVehiclesMainNumVehicles;
CString m_strVehiclesMainMaxSensorCount;
CString m_strVehiclesMainTaskProcessingInterval;
CString m_strVehiclesMain
// [ ... ]
Parameters.cpp
#include "stdafx.h"
#include "prefs.h"
#include "pages.h"
#include "Parameters.h"
//*****************************************************************************
//
// Parameters::Parameters
//
//*****************************************************************************
Parameters::Parameters():
m_strVehiclesMainNumVehicles("")
, m_strVehiclesMainMaxSensorCount("")
, m_strVehiclesMainTaskProcessingInterval("")
// [ ... ]
{
}
The problem is that you're making the pages as local variables in CSAPrefsDialog::OnInitDialog, and those variables are destroyed as soon as you leave the function. You should make them as member variables of your CSAPrefsDialog class. Everything else you're doing looks fine.