Can't acces property c++ - c++

This should be a C++ specific.
I have a property m9ReloadAnim in the header file, I can access it from the constructor, but when I try to access it from an other function I get an error like: EXC_BAD_ACCESS or something like: "The address does not contain an object ".
I have a header class like this:
#ifndef __SWAT__Weapon__
#define __SWAT__Weapon__
#include "cocos2d.h"
class Weapon : public cocos2d::CCSprite
{
private:
cocos2d::CCAnimation *m9ReloadAnim = cocos2d::CCAnimation::create();
public:
Weapon();
~Weapon();
void reloadM9();
};
#endif
And a cpp file like this:
enter code here
#include "Weapon.h"
#include "cocos2d.h"
Weapon::Weapon(){
m9ReloadAnim->setDelayPerUnit(1.1f);
}
Weapon::~Weapon(){
}
void Weapon::reloadM9(){
m9ReloadAnim->setDelayPerUnit(1.1f);
}

You could not initialize variable like this:
cocos2d::CCAnimation *m9ReloadAnim = cocos2d::CCAnimation::create();
Only static const int could be init in class declaration.
Move this init to your ctor:
Weapon::Weapon()
: m9ReloadAnim(cocos2d::CCAnimation::create())
{
m9ReloadAnim->setDelayPerUnit(1.1f);
}
or
Weapon::Weapon()
{
m9ReloadAnim = cocos2d::CCAnimation::create();
m9ReloadAnim->setDelayPerUnit(1.1f);
}

Sometimes the becomes corrupted so you can't tell where errors originate. I would suggest to put a breakpoint at the entry point of each method, and step the code line by line to make sure that it's triggering in the reloadM9 method. Check to see the m9ReloadAnim is NULL or if it points to the object created at initialization. Additionally you need to check if you are using the library properly.

Related

C++ Create Instance of 2nd Class within Instance of 1st Class and Pass 1st Class as Paremeter

I'm using wxWidgets with CodeBlocks, and I'm trying to instantiate a class called FileManager as an attribute of the Frame for wxWidgets, and pass the wxFrame parent to the constructor of FileManager. The objective is to be able to able to refer to the wxFrame from within FileManager. I'm getting an error "FileManager does not name a type". Not sure what I'm doing wrong thanks
The project is called "MullSimple_CB" so the main frame class is "Mull_Simple_CBFrame" Here are the files.
So the main object is a wxFrame object of class MullSimple_CBFrame, defined inside MullSimple_CBMain. The class I want instantiated as a member of that class is FileManager
MullSimple_CBMain.h
#ifndef MULLSIMPLE_CBMAIN_H
#define MULLSIMPLE_CBMAIN_H
#include "non-wx/file_manager.h"
class MullSimple_CBFrame: public wxFrame
{
public:
MullSimple_CBFrame(wxWindow* parent,wxWindowID id = -1);
virtual ~MullSimple_CBFrame();
// ERROR ON THIS LINE:
// "'FileManager' does not name a type"
FileManager fileManager(MullSimple_CBFrame parentFrame);
private
DECLARE_EVENT_TABLE()
};
#endif // MULLSIMPLE_CBMAIN_H
MullSimple_CBMain.cpp
#include "wx_pch.h"
#include "MullSimple_CBMain.h"
#include <wx/msgdlg.h>
#include "non-wx/file_manager.h"
MullSimple_CBFrame::MullSimple_CBFrame(wxWindow* parent,wxWindowID id)
{
FileManager fileManager(this);
}
FileManager.h
#ifndef FILE_MANAGER_H_INCLUDED
#define FILE_MANAGER_H_INCLUDED
#include "../MullSimple_CBMain.h"
class FileManager
{
private:
MullSimple_CBFrame storeMainFrame;
public:
// constructor
FileManager(MullSimple_CBFrame mainFrame);
};
#endif // FILE_MANAGER_H_INCLUDED
FileManager.cpp
#include "file_manager.h"
#include "../MullSimple_CBMain.h"
FileManager::FileManager(MullSimple_CBFrame mainFrame): storeMainFrame(mainFrame))
{
}
Your file_manager.h file includes MullSimple_CBMain.h and the MullSimple_CBMain.h file includes your file_manager.h.
You end up with a never ending chain of includes... which never resolve.
Consider putting forward declarations into a single .h file and then have your .h files only include it as opposed to including the individual class.h files themselves. The only time you need to include the class.h files themselves is if you need the compiler to know about the full definition of the class as opposed to just knowing the class exists at all.

Getting error: expected constructor, destructor, or type conversion before ‘(’ token

I am trying to make functions repository. I have created four files:
Function.hpp, Function.cpp, FunctionsRepository.hpp, FunctionsRepository.cpp
I want to keep pointers to functions in vector of pointers.
//FunctionsRepository.hpp
#ifndef FUNCTIONSREPOSITORY_HPP
#define FUNCTIONSREPOSITORY_HPP
#include <vector>
using namespace std;
class FunctionsRepository {
private:
static vector<double *> pointerToFunctions;
public:
static void addFunction(double * wsk);
};
#endif
//FunctionRepository.cpp
#include "FunctionsRepository.hpp"
void FunctionsRepository::addFunction(double * wsk) {
pointerToFunctions.push_back(wsk);
}
//Functions.hpp
#ifndef FUNCTIONS_HPP
#define FUNCTOINS_HPP
#include "FunctionsRepository.hpp"
int constFunction(int numberOfVehicles);
void linearFunction();
void stepFunction();
#endif
//Funcctions.cpp
#include "Functions.hpp"
double constFunction(double numberOfVehicles){
return numberOfVehicles/2;
}
double (*funcConstant)(double) = constFunction;
//ERROR HERE
FunctionsRepository::addFunction(funcConstant);
I want to add new functions to program as easily as its possible and use it leater in other parts of program.
But I dont get it. Why i am getting this error. The addFunction() method is static, that means I can use it in other classes or parts of program. Vector is static to make sure that is the only one copy for whole program.
Use function wrapper. std::function can stores callable objects. So, your code will contain something like this:
class FunctionsRepository {
private:
// void() - function prototype
static std::vector<std::function<void()>> pointerToFunctions;
public:
static void addFunction(std::function<void()> wsk)
{
pointerToFunctions.push_back(wsk);
}
};
for more information consult official documentation: http://en.cppreference.com/w/cpp/utility/functional/function
I solved It. I received an error because I was calling the FunctionsRepository::addFunction(funcConstant); expression out of any scope. I just created new function to execute this command and thats all.

Create and change game State in runtime

I'm struggling with issue mentioned in the title.For now I'm setting default one in constructor and then i want to change it with my function, however it doesn't seem to work.
void AMyGameModeBase::SwapGameState(AGameStateBase* GameStateVariable)
{
GameStateClass = GameStateVariable->StaticClass();
}
How can I do this properly? Good explanation would be awesome :)
EDIT:
So this is my whole code:
MyGameModeBase.h
#pragma once
#include "GameFramework/GameMode.h"
#include "MyGameModeBase.generated.h"
/**
*
*/
UCLASS()
class PROJECT_API AMyGameModeBase : public AGameMode
{
GENERATED_BODY()
public:
AMyGameModeBase();
UFUNCTION(BlueprintCallable, Category="GameState")
void SwapGameState(AGameStateBase* GameStateVariable);
};
MyGameModeBase.cpp
#include "Project.h"
#include "MyGameModeBase.h"
AMyGameModeBase::AMyGameModeBase()
{
GameStateClass = AGameStateBase::StaticClass();
}
void AMyGameModeBase::SwapGameState(AGameStateBase* GameStateVariable)
{
GameStateClass = GameStateVariable->StaticClass();
}
What I'm doing then is:
1.Open GameMode blueprint
2.Drag from Event begin play and call SwapGameState
3.I'm creating variable that is reference to MyGameState.
4.Then I'm printing with print string name that i get with node "GetGameState" and see that it's not changed.
What i want to achieve is:
1.CreateGameState in runtime
2.Set it to used default game state also in runtime.
The StaticClass function is a static function that you call like this MyStateClass::StaticClass()
What you want is this
void AMyGameModeBase::SwapGameState(AGameStateBase* GameStateVariable)
{
GameStateClass = GameStateVariable->GetClass();
}

Calling function from different files in C++ error

I would like to use one function from Stats.cpp in Application.cpp. Here are my code snippets:
In Stats.h:
#ifndef STATS_H
#define STATS_H
class Stats
{
public:
void generateStat(int i);
};
#endif
In Stats.cpp:
#include Stats.h
void generateStat(int i)
{
//some process code here
}
In Application.cpp:
int main()
{
generateStat(10);
}
I get an "unresolved external symbol" error however I don't know what I else I would need to include in order for Application.cpp. Any thoughts?
In Stats.cpp
you need to define generateStat like following :
#include Stats.h
void Stats:: generateStat(int i) // Notice the syntax, use of :: operator
{
//some process code here
}
Then create object of class Stats, use it to call the public member function generateStat
Stats s;
s.generateStat( 10 ) ;
Build the application using :
g++ -o stats Stats.cpp Application.cpp -I.
generateStat is part of your Stats class. You need to instantiate a Stats object (along with the necessary includes for Stats.h in your main class)
For example,
Stats stat;
stat.generateStat(i);
Also, your function definition needs to include the class name Stats::generateStat.
The same error msg occured 2 weeks ago (at work).
At first glance --- Try:
void Stats::generateStat(int i) {
//some process code here }
The class name was missing. Hence, unresolved.
btw Concerning your header --- another issue, this #ifndef directive should not be necessary cause you should declare Stats only once in a namespace.
#ifndef CLASS_H
#define CLASS_H
#include "Class.h"
#endif
This is a generic example - Usable in cpp files.
EDIT: Now, I saw your invocation (main method in your case). You need an object instance to invoke your method.
Stats* stats = new Stats(); //add a default constructor if not done
stats->generateStat(77);
// any other stats stuff ......
// in posterior to the last use
delete(stats);
In your header:
Stats::Stats(){}; //with an empty body - no need to write it again in the cpp file

C++ - How to call creator class/object

I need to call properties and functions of an object from a different class.
The idea is passing 'this' as a parameter to the other class constructor. E.g.:
instance = ClassName(this);
And then do:
ParentClass parentInstance;
ClassName::ClassName(MainApp _instance){
parentInstance = _instance;
}
However, my compiler says that ParentClass does not name a type. Ideas?
Also, should I use a pointer to save memory? How?
Thanks in advance.
UPDATE:
Ok, sorry for the delay. Here it goes the actual code. First, a simple class.
Game class:
Header file
#ifndef _GAME
#define _GAME
#include "ofMain.h"
class Game{
public:
Game();
~Game();
void hi();
};
#endif
cpp file:
#include "Game.h"
Game::Game(){}
Game::~Game(){}
void Game::hi(){
cout << "hi, I'm game! " << endl;
}
Then, from MainApp I create the object:
- Relevant code on header file:
#ifndef _MAIN_APP
#define _MAIN_APP
#include "ofMain.h"
#include "Game.h"
class MainApp : public ofSimpleApp{
public:
Game game;
};
#endif
Relevant code on the cpp file:
game = Game();
game.hi();
This obviously works as I'm only creating a bloody object. However, problem comes with composition.
I could pass the main app as argument in the constructor, I could pass it via game.setParent(this);... problem is, I can't even define the variable to store the reference to the app.
E.g.: (making it easy/inefficient without pointers or anything)
Game.h:
#define _GAME
#ifndef _GAME
#include "ofMain.h"
#include "MainApp.h"
class Game{
MainApp app;
public:
Game();
~Game();
void hi();
};
#endif
This returns a "does not name a type" error and declaring class MainApp returns an "incomplete type" error
I'm sure I'm doing something dumb.
UPDATE 2:
The problem with that method is that I can't call a function of the pointed object now.
This is Game.h:
#ifndef _GAME
#define _GAME
#include "ofMain.h"
class MainApp;
class Game{
public:
Game();
Game(MainApp* _app);
~Game();
void hi();
MainApp* app;
};
#endif
As you see, app (of the type MainApp) is passed as a parameter. That's fine, MainApp exists as it's the forward declaration. However, when I try to call any of app's functions I can't (compiler error saying Request for member appHi in .... which is non-class type 'MainApp'.
MainApp is NOT included in Game.h but Game.h IS included in MainApp.h.
Ideas?
The problem is you have a circular reference - Game includes MainApp, and MainApp includes game. You need a 'forward declaration', as per the example by DeadMG.
See here.
It's called composition and is a common pattern. It's highly efficient in both semantics and in terms of runtime speed/memory footprint.
Your code example is a little too much pseudocode for me to read it correctly. Let me show you how it's done.
class X;
class Y {
...
void DoSomething(X* x, ... args);
};
class X {
Y y;
void DoSomething() {
y.DoSomething(this, args);
}
};
I think there may be two issues here:
1) You need to declare the ParentClass (i.g. #include its .hpp-file) before using it
2) The assignment "parentInstance = _instance" will invoke the assignment operator, which i'm guessing is not what you want. let "parentInstance" be a pointer instead.
Note the section on "#include."
http://www.cplusplus.com/doc/tutorial/program_structure/
After the "Intro to the C++ Language" section look for the verbiage about #include.
http://www.cprogramming.com/tutorial/lesson1.html
Namespaces:
http://www.tenouk.com/Module23.html
HTH
That's not how things work in C++. Unlike javascript, you cannot inject methods or fields into existing objects at runtime.
Madsen is on the right track here, but we need more code; What is the class heirarchy of ParentClass, ClassName and SaleraApp. Which classes are base and/or dervied?
When you write: parentInstance = _instance; the compiler will try to generate a default copy constructor if one is not defined. Your problem might be that you are trying to create a dervied class object from a base class pointer.
Also, "this" is a pointer.
If all you need to do is use functions and data members of another class, read up on the friend keyword. It will allow access to class members from other classes.
UPDATE: Alternatively, store a pointer or reference to the object you need access to, and make getters for data members and make the functions public... but I get the feeling this is not what you're after...