How to pass a reference to an object to another class - c++

I'm trying to pass a reference to an object from my main.cpp to menux.cpp however I'm getting this error:
error: conflicting declaration 'MenuX alpha4'
MenuX(alpha4);
main.cpp
#include "MenuX.h"
Adafruit_AlphaNum4 alpha4 = Adafruit_AlphaNum4();
MenuX(alpha4);
MenuX.h
#ifndef MENUX_H
#define MENUX_H
#include "Adafruit_LEDBackpack.h"
#include <Adafruit_GFX.h> // Core graphics library
class MenuX
{
public:
MenuX(Adafruit_AlphaNum4 *alpha4);
void addX();
private:
Adafruit_AlphaNum4 *xLed;
};
#endif
MenuX.cpp
#include "MenuX.h"
MenuX::MenuX(Adafruit_AlphaNum4 *alpha4) {
xLed = alpha4;
}
void MenuX::addX()
{
xLed->writeDigitAscii(0, 'X');
xLed->writeDigitAscii(1, 'X');
xLed->writeDigitAscii(2, 'X');
xLed->writeDigitAscii(3, 'X');
xLed->writeDisplay();
}

You don't have your main code inside of a main function
You can create the alpha4 in main without creating and assigning a temporary
The MenuX constructor takes a pointer so you need to pass &alpha4
Not an error but probably a mistake, you don't use the MenuX you've created
#include "MenuX.h"
int main() {
Adafruit_AlphaNum4 alpha4;
MenuX menu(&alpha4); // added & and object name
}

Related

C++.Passing to functions.Syntax issue

I am pursuing some interest in c++ programming by way of self instruction. I am working on some basic stuff for now and am currently having issue getting my classes talking/instantiated?.
I am trying to get my main cpp file to compile alongside a header and call to some class functions through the main using a more efficient command method.
I am stuck and would appreciate some help. I will include both files. I am just trying to get a return value from the header by calling the function.
error:
main.cpp:6.21 error: cannot call member function 'void myClass::setNumber(int) without object
the code works when compiled with the main, so it is something with the 'scope resolution operator' i think. First is main.cpp
#include <iostream>
#include "myClass.h"
using namespace std;
int main(){
myClass::setNumber(6);
{
return number;
}
}
Then my header file myClass.h
// MyClass.h
#ifndef MYCLASS_H
#define MYCLASS_H
class myClass {
private:
int number;//declares the int 'number'
float numberFloat;//declares the float 'numberFloat
public:
void setNumber(int x) {
number = x;//wraps the argument "x" as "number"
}
void setNumberFloat(float x) {
numberFloat = x;
}
int getNumber() {//defines the function within the class.
number += 500;
return number;
}
float getNumberFloat() {//defines the function
numberFloat *= 1.07;
return numberFloat;
}
};
#endif
Any help?
The error message says everything:
cannot call member function 'void myClass::setNumber(int)' without object
You need to create an object first:
myClass obj;
then call the class method on that object:
obj.setNumber(6);
The value 6 will get assigned to the number field of the obj variable.

G++ - Undefined Reference to member function that is defined

I am currently working on a virtual run time environment program that is at a very early stage, i am prevented from continuing my work due to a linker error when using my makefile, provided below. The error i am receiving is:
g++ controller.o processor.o test.o -o final
controller.o: In function `Controller::run()':
controller.cpp:(.text+0x1e0): undefined reference to
Processor::codeParams(char)'
controller.o: In function `Controller::fetch()':
controller.cpp:(.text+0x290): undefined reference to `Controller::pc'
controller.cpp:(.text+0x299): undefined reference to `Controller::pc'
collect2: error: ld returned 1 exit status
makefile:16: recipe for target 'final' failed
make: *** [final] Error 1
I am unsure as to why i get this error as i thought i had defined these things in the source file corresponding to the header. All files will be given below so that the program can be compiled.
test.cpp:
#include <iostream>
#include <vector>
#include "includes/controller.h"
using namespace std;
int main()
{
vector<char> prog = {0x0};
Controller contr(prog);
cout << "Error Code: " << contr.run() << endl;
return 0;
}
controller.cpp:
/*
Author(s): James Dolan
File: controller.cpp
Build: 0.0.0
Header: includes/controller.h
DoLR: 21:39 11/1/2017
Todo: n/a
*/
#include "includes/controller.h"
Controller::Controller(vector<char> prog)
{
printf("Program:"); //Display program
for(auto i : program)
{
printf("%02X", i);
}
printf("\n");
Controller::program = program;
}
Controller::~Controller ()
{
}
int Controller::run()
{
bool runFlag = true;
int errorCode = 0;
char curCode;
vector<char> curInstr;
int paramRef;
while(runFlag)
{
curCode = fetch();
printf("curCode:%02X\n", curCode);
curInstr.push_back(curCode);
paramRef = proc.codeParams(curCode);
if (paramRef == 0xffff){runFlag = false; continue;} //Check if shutdown signal was returned, if so shutdown
printf("opcode good\n");
for(int i; i<paramRef; i++){curInstr.push_back(fetch());}
}
return errorCode;
}
char Controller::fetch()
{
return program[pc++]; //Return next instruction then increment the program counter
}
controller.h:
/*
Author(s): James Dolan
File: controller.h
Source: ../controller.cpp
DoLR: 21:39 11/1/2017
Todo: n/a
*/
#ifndef CONTROLLER_H
#define CONTROLLER_H
#include <iostream>
#include <vector>
#include <cstdlib>
#include "processor.h"
using namespace std;
class Controller{
public:
Controller(vector<char> prog);
~Controller();
int run();
protected:
private:
vector<char> program;
static int pc;
char fetch();
Processor proc();
};
#endif
processor.cpp:
#include "includes/processor.h"
Processor::Processor()
{
}
Processor::~Processor()
{
}
int codeParams(char code)
{
switch(code)
{
case 0x0: //Halt
return 0;
default:
printf("[ERROR!] Invalid opcode [%02X]", code);
return 0xffff; //Return shutdown signal
}
}
processor.h:
#ifndef PROCESSOR_H
#define PROCESSOR_H
#include <iostream>
#include <cstdlib>
class Processor{
public:
Processor();
~Processor();
int codeParams(char code);
protected:
private:
};
#endif
All if any help is appreciated massively as it will help me to continue with my passion of developing a fully fledged open-source virtual runtime enviroment like the java vm, thank you for your time.
In Controller.cpp you need a int Controller::pc; or int Controller::pc = 0;
In the header file you declared a static int named pc that exists somewhere. It needs to actually exist in a translation unit somewhere (in this case Controller.cpp) so that when the linker tries to find it... it exists.
In Processor.cpp your signature should look like int Processor::codeParams(char code) to let the compiler know that is Processor's codeParams and not a random function named codeParams that happens to also take a character.
For the member function Processor::codeParams you should define it as:
int Processor::codeParams(char code)
// ~~~~~~~~~~~
{
...
}
Otherwise it's just a normal (non–member) function.
For the static member Controller::pc you should define it outside of the class definition, in controller.cpp.
// Controller.h
class Controller {
...
private:
static int pc;
};
// controller.cpp
int Controller::pc;

Arduino C++ file - class instantiation fails when setting a private member variable in the constructor

I'm using the Arduino IDE 1.0.5-r2 and trying to create a class with two member variables, _pinA and _pinB. When I call the constructor from my Arduino sketch, I get this error:
RotaryEncoderReader.cpp:6: error: request for member '_pinB' in 'this', which is of non-class type 'RotaryEncoderReader* const'
The constructor can be called from a regular C++ files compiled using GCC, and there are no errors. Am I missing something about how to use a class constructor with an Arduino?
Here is the class header:
#ifndef RotaryEncoderReader_h
#define RotaryEncoderReader_h
#include "Arduino.h"
class RotaryEncoderReader {
private:
int _pinA;
int _pinB;
volatile long encoderPos;
public:
RotaryEncoderReader( int newPinA, int newPinB );
void doEncoderA();
void doEncoderB();
long getPosition();
};
#endif
Here's the implementation:
#include "RotaryEncoderReader.h"
RotaryEncoderReader::RotaryEncoderReader( int newPinA, int newPinB )
: _pinA(newPinA),
_pinB(newPinB),
encoderPos(0)
{
}
void RotaryEncoderReader::doEncoderA()
{
//Irrelevant
}
void RotaryEncoderReader::doEncoderB()
{
//Irrelevant
}
long RotaryEncoderReader::getPosition()
{
return _pinA + _pinB;
}
And here's the Arduino sketch:
#include <RotaryEncoderReader.h>
int pinA = 2;
int pinB = 3;
RotaryEncoderReader reader(pinA, pinB);
void setup()
{
}
void loop()
{
}

Why does compiler tries to pass a pointer to reference rather than pointer in this code snippet?

I have 5 files:
ExecutionStrategyInterface.h
ExecutorInterface.h
TaskCollectionInterface.h
TaskExecutor.h
TaskExecutor.cpp.
TaskExecutor implements the following member method:
void TaskExecutor::execute(TaskCollectionInterface* tci, const ExecutionStrategyInterface& es) {
es.execute(tci);
}
At compile time, the compiler calls a member method with a parameter of type pointer to a reference(i.e: mylib::core::TaskCollectionInterface*&).
TaskExecutor.cpp: In member function ‘virtual void mylib::core::TaskExecutor::execute(mylib::core::TaskCollectionInterface*, const mylib::core::ExecutionStrategyInterface&)’:
TaskExecutor.cpp:16: error: no matching function for call to ‘mylib::core::ExecutionStrategyInterface::execute(mylib::core::TaskCollectionInterface*&) const’
./././ExecutionStrategyInterface.h:24: note: candidates are: virtual void mylib::core::ExecutionStrategyInterface::execute(TaskCollectionInterface*) const
make: *** [TaskExecutor.o] Error 1
Can anyone explain me what is happening here please ?
Classes:
ExecutionStrategyInterface.h
#ifndef _EXECUTIONSTRATEGYINTERFACE_H_
#define _EXECUTIONSTRATEGYINTERFACE_H_
class TaskCollectionInterface;
namespace mylib { namespace core {
/**
* Interface for executing a strategy.
*/
class ExecutionStrategyInterface {
public:
/**
* Executes a strategy
*/
virtual void execute(TaskCollectionInterface* tci) const = 0;
};
}} // namespaces
#endif // _EXECUTIONSTRATEGYINTERFACE_H_
TaskCollectionInterface.h
#ifndef _TASKCOLLECTIONINTERFACE_H_
#define _TASKCOLLECTIONINTERFACE_H_
#include "./ExecutionStrategyInterface.h"
namespace mylib { namespace core {
/**
* Interface for a collection of tasks.
*/
class TaskCollectionInterface {
public:
~TaskCollectionInterface();
};
}} // namespaces
#endif // _TASKCOLLECTIONINTERFACE_H_
ExecutorInterface.h
#ifndef _EXECUTORINTERFACE_H_
#define _EXECUTORINTERFACE_H_
class ExecutionStrategyInterface;
class TaskCollectionInterface;
#include "./ExecutionStrategyInterface.h"
#include "./TaskCollectionInterface.h"
namespace mylib { namespace core {
/**
* Interface for an executor.
*/
class ExecutorInterface {
public:
virtual void execute(TaskCollectionInterface* tci, const ExecutionStrategyInterface& es) = 0;
~ExecutorInterface();
};
}} // namespaces
#endif // _EXECUTORINTERFACE_H_
TaskExecutor.h
#ifndef _TASKEXECUTOR_H_
#define _TASKEXECUTOR_H_
#include "./ExecutorInterface.h"
class TaskCollectionInterface;
class ExecutionStrategyInterface;
namespace mylib { namespace core {
/**
* Task Runner.
*/
class TaskExecutor: public ExecutorInterface {
public:
virtual void execute(TaskCollectionInterface* tci, const ExecutionStrategyInterface& es) = 0;
};
}} // namespaces
#endif // _TASKEXECUTOR_H_
TaskExecutor.cpp
#include "./TaskExecutor.h"
#include "./ExecutionStrategyInterface.h"
#include "./TaskCollectionInterface.h"
namespace mylib { namespace core {
void TaskExecutor::execute(TaskCollectionInterface* tci, const ExecutionStrategyInterface& es) {
es.execute(tci);
}
}} // namespaces
This is confusing because you are forward-declaring the class outside the namespace, so you are ending up with two different classes with the same name. You'll want something like this instead:
namespace mylib {
namespace core {
class TaskCollectionInterface;
class ExecutionStrategyInterface {
.
.
.
};
}
}
The way you have it now, your execute method is taking a pointer to ::TaskCollectionInterface instead of mylib::core::TaskCollectionInterface.
When gcc says type&, it's just its shorthand for saying that you are passing an lvalue so that you know that functions taking a non-const reference are viable candidates.
The problem that you have is that you have declared the method as taking a ::TaskCollectionInterface, but the error message indicates that you are attempting to pass a ::mylib::core::TaskCollectionInterface.
You have a declaration of ::mylib::core::TaskCollectionInterface in TaskCollectionInterface.h that masks the declaration of ::TaskCollectionInterface in the namespace mylib::core.
This is because you are passing a pointer TaskCollectionInterface* tci to the ExecutionStrategyInterface::execute method, while it wants a reference. So you have to dereference that pointer when passing it to that function:
void TaskExecutor::execute(TaskCollectionInterface* tci, const ExecutionStrategyInterface& es) {
es.execute(*tci);
}

C++ forward declaration error

I have an error that goes like this
In file included from Level.hpp:12,
from main.cpp:4:
Corridor.hpp: In method `void Game::Corridor::update()':
Corridor.hpp:41: invalid use of undefined type `class Game::Level'
Corridor.hpp:13: forward declaration of `class Game::Level'
Corridor.hpp:42: invalid use of undefined type `class Game::Level'
Corridor.hpp:13: forward declaration of `class Game::Level'
Corridor.hpp:43: invalid use of undefined type `class Game::Level'
Corridor.hpp:13: forward declaration of `class Game::Level'
Corridor.hpp:44: invalid use of undefined type `class Game::Level'
Corridor.hpp:13: forward declaration of `class Game::Level'
Corridor and Level are ...
// Corridor.hpp
#ifndef GAME_CORRIDOR_HPP
#define GAME_CORRIDOR_HPP
#include <Moot/Math.hpp>
//#include <Level.hpp>
#include <GameWindow.hpp>
namespace Game
{
class Level; // <-- LINE 13
class Corridor
{
static const unsigned int defaultLevelDepth = 800;
Moot::Math::Vector3D wp1, wp2, wp3, wp4;
Moot::Math::Vector2D sp1, sp2, sp3, sp4;
Level * p_level;
public:
Corridor(Moot::Math::Vector3D setFirstPoint, Moot::Math::Vector3D setSecondPoint)
{
wp1 = setFirstPoint;
wp2 = setSecondPoint;
wp3 = setFirstPoint;
wp3.z += defaultLevelDepth;
wp4 = setSecondPoint;
wp4.z += defaultLevelDepth;
}
void update() {
sp1 = p_level->getLevelCamera().convert3DVectorWithScreenAlgorithm(wp1); // <- LINE 41 etc.
sp2 = p_level->getLevelCamera().convert3DVectorWithScreenAlgorithm(wp2);
sp3 = p_level->getLevelCamera().convert3DVectorWithScreenAlgorithm(wp3);
sp4 = p_level->getLevelCamera().convert3DVectorWithScreenAlgorithm(wp4);
//p_level->getLevelCamera();
}
void draw()//const
{
Moot::Color tempColor;
windowInstance().graphics().drawQuad( sp1.x, sp1.y, tempColor,
sp2.x,sp2.y, tempColor,
sp3.x, sp3.y, tempColor,
sp4.x,sp4.y, tempColor, 1);
}
void setLevel(Level* setLevel) {
p_level = setLevel;
}
};
}
#endif
and
// Level.hpp
#ifndef GAME_LEVEL_HPP
#define GAME_LEVEL_HPP
#include <Moot/Forward.hpp>
#include <Moot/Window.hpp>
#include <Moot/Math.hpp>
#include <GameWindow.hpp>
#include <Camera.hpp>
#include <Corridor.hpp>
#include <Player.hpp>
#include <vector>
namespace Game
{
class Level
{
typedef Corridor* p_corridor;
typedef std::vector<p_corridor> CorridorList;
typedef CorridorList::reverse_iterator ReverseCorridorItter;
CorridorList m_map;
Camera m_camera;
Player m_player;
public:
Level()
{
m_player.setLevel(this);
// Lots of vertices being defined into m_map.
// Loop through and set camera
ReverseCorridorItter rit;
for(rit = m_map.rbegin(); rit != m_map.rend(); rit++)
(*rit)->setLevel(this);
}
~Level()
{
ReverseCorridorItter rit;
for(rit = m_map.rbegin(); rit != m_map.rend(); rit++)
delete (*rit);
m_map.clear();
}
void update()
{
// Temp delete when input and player are implimented.
if(pad[0].buttons & PAD_UP)
m_camera.updateTargetOffsets(0, -2);
if(pad[0].buttons & PAD_DOWN)
m_camera.updateTargetOffsets(0, 2);
if(pad[0].buttons & PAD_LEFT)
m_camera.updateTargetOffsets(-2, 0);
if(pad[0].buttons & PAD_RIGHT)
m_camera.updateTargetOffsets(2, 0);
m_player.update();
ReverseCorridorItter rit;
for (rit = m_map.rbegin(); rit != m_map.rend(); rit++)
(*rit)->update();
}
void draw() // const // EH!!! wtf ReverseIter isn't a member
{
m_player.draw();
ReverseCorridorItter rit;
for (rit = m_map.rbegin(); rit != m_map.rend(); rit++)
(*rit)->draw();
}
Camera& getLevelCamera() {
return m_camera;
}
};
}
#endif
The pointer is being set as far as I can tell, but when I try to access a function from Level, BOOM!
Thanks.
PS: The compiler is gcc 2.95.2 if that makes a difference.
EDIT
Updated with complete code.
You are #include-ing Level's complete declaration:
#include <Level.hpp>
...and then you try to forward-declare Level:
namespace Game
{
class Level;
Don't do this. Choose one or the other. (edit) Or at least put the forward-declaration before the #include-ion of the complete declaration. If all you're doing in game_corridor.hpp is setting pointers to a Level, then a forward declare should do fine. If however you need to call functions on Level from within the HPP file, then you'll need to #include the complete declaration.
EDIT2:
Based on your clarifying edit to your OP, you must #include the complete declaration of Level, and not try to use a forward declaration.
If you forward-declare Game::Level then don't #include it. In a not-so-related note, use #include "header.hpp", not #include <header.hpp>.
Edit as per your updates: Bring the definition of Game::Corridor::update() outside the header and into an implementation file. This way the compile need not know anything about Game::Level apart from the fact that it exists and it's a type.
The problem is that Corridor doesn't know what a Level is, because it can't really #include Level.hpp, because Level.hpp is what #included Corridor.hpp.
The underlying problem is that you're trying to #include a source file. The really underlying problem is that you're using #include when you haven't separated your code into source files and header files. Here's how to split it up. (I'm assuming you're familiar with compiling source files into object files, then linking them into executables.)
Corridor.hpp:
#ifndef GAME_CORRIDOR_HPP
#define GAME_CORRIDOR_HPP
#include <Moot/Math.hpp>
#include <Level.hpp>
namespace Game
{
class Level;
class Corridor
{
static const unsigned int defaultLevelDepth = 800;
Moot::Math::Vector3D wp1, wp2, wp3, wp4;
Moot::Math::Vector2D sp1, sp2, sp3, sp4;
Level * p_level;
public:
Corridor(Moot::Math::Vector3D setFirstPoint, Moot::Math::Vector3D setSecondPoint);
void update();
void draw();
void setLevel(Level* setLevel);
};
}
#endif
Corridor.cpp:
#include "Corridor.hpp"
namespace Game
{
Corridor::Corridor(Moot::Math::Vector3D setFirstPoint, Moot::Math::Vector3D setSecondPoint)
{
wp1 = setFirstPoint;
wp2 = setSecondPoint;
wp3 = setFirstPoint;
wp3.z += defaultLevelDepth;
wp4 = setSecondPoint;
wp4.z += defaultLevelDepth;
}
void Corridor::update()
{
sp1 = p_level->getLevelCamera().convert3DVectorWithScreenAlgorithm(wp1);
sp2 = p_level->getLevelCamera().convert3DVectorWithScreenAlgorithm(wp2);
sp3 = p_level->getLevelCamera().convert3DVectorWithScreenAlgorithm(wp3);
sp4 = p_level->getLevelCamera().convert3DVectorWithScreenAlgorithm(wp4);
}
// and so on
}