Object is wrong type - c++

Basically for some reason new object is wrong type. All source code is on github https://github.com/teuro/sfml-radar. If it's help please fork at will.
I have following class:
#ifndef _VIEW_HPP
#define _VIEW_HPP
#include <iostream>
#include "sfml_drawsurface.hpp"
class View {
protected:
View(Drawsurface& d) : drawer(d) {
std::clog << "View::View()" << std::endl;
}
Drawsurface& drawer;
virtual void draw() = 0;
};
#endif
That is base class for all different kind of views. Now I have derived sub-class
#ifndef _GAME_VIEW_HPP
#define _GAME_VIEW_HPP
#include <vector>
#include <iostream>
#include <typeinfo>
#include "view.hpp"
#include "../models/game.hpp"
class Gameview : public View {
public:
Gameview(Drawsurface& d);
~Gameview();
void draw();
private:
Drawsurface& drawer;
};
#endif // _GAME_VIEW_HPP
Then abstract class Drawsurface
/**
* drawsurface base for all graphics pure abstract
* provide only interface quite high-level
* 2014/06/02
* Juha Teurokoski
**/
#ifndef _DRAWSURFACE_HPP
#define _DRAWSURFACE_HPP
#include <string>
#include "../models/point.hpp"
class Drawsurface {
public:
bool font_loaded;
virtual void rectangleColor(Point& a, Point& b, unsigned int color) = 0;
virtual void lineColor(Point& a, Point& b, unsigned int color) = 0;
virtual void circleColor(Point& a, unsigned int rad, unsigned int color) = 0;
virtual void trigonColor(Point& a, Point& b, Point& c, unsigned int color) = 0;
virtual void trigonColor(Point& a, unsigned int size, unsigned int color) = 0;
virtual void load_font(std::string font) = 0;
virtual void draw_picture(std::string tiedosto, Point& a, bool center = false) = 0;
virtual void draw_text(std::string text, Point& a, unsigned int color = 0) = 0;
virtual int get_fontsize() = 0;
virtual void flip() = 0;
virtual void clear_screen() = 0;
virtual ~Drawsurface() { }
};
#endif
Now if I create new instance of sfml_drawsurface which is sub-class of Drawsurface. For some reason new object is Drawsuface istead of sfml_drawsurface. Below is sfml_drawsurface class.
#ifndef SFML_DRAWSURFACE_HPP
#define SFML_DRAWSURFACE_HPP
/**
* sfml-drawsurface provides basic drawing, pictures and text
* require drawsurface
* 2014/06/02
* Juha Teurokoski
**/
#include "drawsurface.hpp"
#include <vector>
#include <stdexcept>
#include <iostream>
#include <SFML/Graphics.hpp>
class sfml_drawsurface : public Drawsurface {
public:
sfml_drawsurface(sf::RenderWindow& window);
~sfml_drawsurface();
void rectangleColor(Point& a, Point& b, unsigned int color);
void circleColor(Point& a, unsigned int rad, unsigned int color);
void lineColor(Point& a, Point& b, unsigned int color);
void trigonColor(Point& a, Point& b, Point& c, unsigned int color);
void trigonColor(Point& a, unsigned int _size, unsigned int color);
void draw_picture(std::string tiedosto, Point& a, bool center = false);
void draw_text(std::string text, Point& a, unsigned int color);
void load_font(std::string font);
void clear_screen();
int get_fontsize();
void flip();
protected:
private:
sf::RenderWindow& window;
sf::Font font;
sf::Color active;
sf::Color normal;
};
#endif // SFML_DRAWSURFACE_HPP
I create new object like this:
sfml_drawsurface drawer(window);
this->gameview = new Gameview(drawer);
std::clog << typeid(drawer).name() << std::endl;
And everything seems to be right, because std::clog outout is '16sfml_drawsurface'.
Next place is draw-method then happens something really weird.
Same print is now '11Drawsurface'.

Looks like Mike had the right idea. From your Program.cpp file you have in your constructor:
Program::Program() {
Game game;
...
this->gamecontroller = new Gamecontroller(game); //Probably also bad
sfml_drawsurface drawer(window);
this->gameview = new Gameview(drawer);
}
The problem is that drawer ceases to exist once the constructor is finished leaving you with a dangling reference and undefined behaviour. Looks like you may have the same problem with the game variable.
Solution is to not have them as local variables but as either class members (preferred) or dynamically allocated (it depends how long you need to have them around).

Related

C++ out-of-line definition Pure Virtual Method

I have 4 files car.cpp, car.h, motorvehicle.h and vehicle.h. I am programming in the QT-creator environment.
The issue i am having is:
error: out-of-line definition of 'getSafetyRating' does not match any declaration in 'vehicle::Car'
int Car::getSafetyRating()
Here are the program files for reference, i am new to learning c++ and would really appreciate the help! Cheers Alex. I Apologies in advance for any repost of problems if any.
vehicle.h
#ifndef VEHICLE_H
#define VEHICLE_H
#include <string>
namespace vehicle
{
class Vehicle
{
public:
Vehicle(int numberOfPassengers,
int topSpeed,
int numberOfWheels,
std::string color = "red");
virtual ~Vehicle();
virtual std::string getColor();
virtual int getTopSpeed();
virtual int getNumberOfWheels();
virtual int getNumberOfPassengers();
virtual int getSafetyRating() = 0;
protected:
int m_numberOfPassengers;
int m_topSpeed;
int m_numberOfWheels;
std::string m_color;
};
}
#endif // VEHICLE_H
motorvehicle.h
#ifndef MOTORVEHICLE_H
#define MOTORVEHICLE_H
#include "vehicle.h"
namespace vehicle
{
class MotorVehicle : public Vehicle
{
public:
MotorVehicle(int numberOfPassengers,
int topSpeed,
int numberOfWheels,
double kilometresPerLitre);
MotorVehicle(int numberOfPassengers,
int topSpeed,
int numberOfWheels,
std::string color,
double kilometresPerLitre);
virtual ~MotorVehicle();
virtual double getKilometresPerLitre();
protected:
double m_kmpl;
};
}
#endif // MOTORVEHICLE_H
car.h
#ifndef CAR_H
#define CAR_H
#include "motorvehicle.h"
namespace vehicle
{
class Car : public MotorVehicle
{
public:
Car(int numberOfPassengers,
int topSpeed,
double kilometresPerLitre,
int numberOfAirBags = 2,
bool abs = true,
int numberOfWheels = 4);
Car(int numberOfPassengers,
int topSpeed,
double kilometresPerLitre,
std::string color,
int numberOfAirBags = 2,
bool abs = true,
int numberOfWheels = 4);
virtual ~Car();
virtual int getNumberOfAirBags();
virtual bool hasAutomaticBreakingSystem();
protected:
int m_numberOfAirBags;
int m_abs;
};
}
#endif // CAR_H
car.cpp
#include "car.h"
using namespace vehicle;
Car::Car(int numberOfPassengers,
int topSpeed,
double kilometresPerLitre,
int numberOfAirBags,
bool abs,
int numberOfWheels) :
MotorVehicle(numberOfPassengers, topSpeed, numberOfWheels, kilometresPerLitre),
m_numberOfAirBags(numberOfAirBags),
m_abs(abs)
{
}
Car::Car(int numberOfPassengers,
int topSpeed,
double kilometresPerLitre,
std::string color,
int numberOfAirBags,
bool abs,
int numberOfWheels):
MotorVehicle(numberOfPassengers, topSpeed, numberOfWheels,color, kilometresPerLitre),
m_numberOfAirBags(numberOfAirBags),
m_abs(abs)
{
}
Car::~Car()
{
}
int Car::getNumberOfAirBags()
{
return m_numberOfAirBags;
}
bool Car::hasAutomaticBreakingSystem()
{
return m_abs;
}
int Car::getSafetyRating()
{
int SafetyRating = 0;
if (m_numberOfAirBags >= 4)
{
SafetyRating += 3;
}
else if (m_numberOfAirBags >= 2)
{
SafetyRating += 2;
}
else if (m_numberOfAirBags > 0)
{
SafetyRating += 1;
}
if (m_abs)
{
SafetyRating += 2;
}
return SafetyRating;
}
Your car class does not have a getSafetyRating declared in the .h file, and the pure virtual function in vehicle requires it. When you declare something pure virtual, ie func() = 0, you basically say that any class that inherits from it MUST implement this function.
So both the motor vehicle class, and the car class must at the very least declare the getSafetyRating function.
One thing that should solve this is to add this to Motor Vehicle:
virtual int getSafetyRating() = 0;
and in the car.h write
virtual int getSafetyRating()
Add declaration of function int getSafetyRating() in your car.h

Inheritance in C++ , recall base function and function don't change value

In library TOADO.h
#ifndef _TOADO_H
#define _TOADO_H
class TOADO
{
public:
TOADO();
void SoDiem(int soluong);
void addToaDo(POINT *toado);
void setWidth(int width);
public:
int SoLuong;
int Width;
POINT* ToaDo;
};
#endif
In library FIGURE.h
#include "TOADO.h"
#ifndef _FIGURE_H
#define _FIGURE_H
class FIGURE:public TOADO
{
public :
FIGURE();
virtual void Draw(Graphics &graphics);
};
#endif
IN LINE.h
#include "FIGURE.h"
#ifndef _LINE_H
#define _LINE_H
class LINE:public FIGURE
{
public:
LINE(const Color &clr,POINT* line );
void Draw(Graphics &graphics);
private:
TOADO Line;
Color color;
};
#endif
int main()
{
LINE A(color, point); // char color , point is array point
A.setWidth(2);// function setWidth() in class TOADO
}
why i recall base function A.setWidth(2) but function A.Width() still return Width = 1, it don't change Width = 2;
everyone can explain for me and instruct for me how to fix it .
thanks.
so sorry, my english very bad, i don't can't describe to everyone understand
The problem is function setWidth().
it's my code
https://www.mediafire.com/?28dzv62x1kvxci2

Invalid conversion c++

I get this error
invalid conversion from 'GameObject*' to 'std::vector::value_type {aka SDLGameObject*}' [-fpermissive]
This is my code I don't know what is wrong because in my class MainMenu it works this is my class Playstate.cpp
bool PlayState::onEnter()
{
SDL_ShowCursor(1);
//parse the state
TheTextureManager::Instance()->load("assets/button.png", "test", TheGame::Instance()->getRenderer());
GameObject* pGameObject1 = TheGameObjectFactory::Instance()->create("MenuButton");
pGameObject1->load(new LoaderParams(120, 300, 400, 100, "test", 4, 4, 4));
m_gameObjects.push_back(pGameObject1);
}
GameObject.h
#include "LoaderParams.h"
#include <string>
using namespace std;
class GameObject {
public:
virtual void draw() = 0;
virtual void update() = 0;
virtual void clean() = 0;
virtual void load(const LoaderParams* pParams)=0;
protected:
GameObject() {}
virtual ~GameObject() {}
};
#endif /* GAMEOBJECT_H_ */
SDLGameObject.h
#ifndef SDLGAMEOBJECT_H_
#define SDLGAMEOBJECT_H_
#pragma once
#include "GameObject.h"
#include "LoaderParams.h"
#include "TextureManager.h"
#include "Vector2D.h"
class SDLGameObject : public GameObject {
public:
SDLGameObject();
virtual void draw();
virtual void update();
virtual void clean(){}
virtual void load(const LoaderParams* pParams);
Vector2D& getPosition() { return m_position; }
virtual int getWidth() { return m_width; }
virtual int getHeight() { return m_height; }
protected:
Vector2D m_position;
Vector2D m_velocity;
Vector2D m_acceleration;
int m_width;
int m_height;
int m_currentRow;
int m_currentFrame;
std::string m_textureID;
};
#endif /* SDLGAMEOBJECT_H_ */
MainMenuState.cpp here it does work!!
bool MainMenuState::onEnter()
{
SDL_ShowCursor(1);
//parse the state
TheTextureManager::Instance()->load("assets/button.png", "playbutton" , TheGame::Instance()->getRenderer());
TheTextureManager::Instance()->load("assets/exit.png", "exitbutton" , TheGame::Instance()->getRenderer());
GameObject* pGameObject = TheGameObjectFactory::Instance()->create("MenuButton");
GameObject* pGameObject1 = TheGameObjectFactory::Instance()->create("MenuButton");
pGameObject->load(new LoaderParams(120, 150, 400, 100, "playbutton", 0, 1, 2));
pGameObject1->load(new LoaderParams(120, 300, 400, 100, "exitbutton", 1, 2, 2));
m_gameObjects.push_back(pGameObject);
m_gameObjects.push_back(pGameObject1);
m_callbacks.push_back(0);
m_callbacks.push_back(s_menuToPlay);
m_callbacks.push_back(s_exitFromMenu);
//set callbacks for menu items
setCallbacks(m_callbacks);
std::cout << "Entering MainMenuState\n";
return true;
}
SDLGameObject derives from the base class GameObject. Your vector m_gameObjects stores pointers to SDLGameObject, but you are giving it a pointer to a GameObject.
This conversion is not possible as a GameObject is not necessarily an SDLGameObject.
If you are sure that this is the case you can do this:
SDLGameObject* p = dynamic_cast<SDLGameObject>(pGameObject1);
if(!p) {
// pGameObject1 is actually not an SDLGameObject
}
m_gameObjects.push_back(p);
Or change the definition of m_gameObjects to store pointers to GameObject.

C++ preprocessor directive issue

I have a stream class with following functions :
void writeInt(int value); //old function
void writeInt(int value, char* lable); //new function
we've used the writeInt() old function in lot of places. without changing the existing usage
I tried to replace the old function with the new function using following:
#define writeInt(x) writeInt(x,#x)
but it still calls the old functions not the new functions!.
Update:(working test-case)
// IStream.h
#include <stdio.h>
class IWStream {
public:
IWStream(char* path);
virtual ~IWStream();
virtual void writeInt( int iValue, char* szlable= 0 );
private:
FILE* _file;
};
//DataObject.h
class DataObject {
public:
DataObject(int value);
virtual ~DataObject(){};
void writeData(IWStream *stream);
private:
int _value;
};
//DataObject.cpp
#include "DataObject.h"
#include "IStream.h"
#define writeInt(x) writeInt(x,#x)
DataObject::DataObject(int value)
{
_value = value;
}
void DataObject::writeData(IWStream *stream)
{
stream->writeInt(_value);
}
//main.cpp
int main(){
IWStream stream("D://test.txt");
DataObject data(10);
data.writeData(&stream);
return 0;
}

Simple reference variable assignment causing segfault in global pointer to object?

I'm getting a segfault on line 15 of my .cpp file. I'm not sure why. Various code snippets:
explosionhandler.h:
class explosionhandler {
public:
struct explosion {
...
};
vector<struct explosion> explosions;
struct explosion_type {
...
};
vector<struct explosion_type> type;
int num_types;
explosionhandler();
~explosionhandler();
void registerexplosion(int& ttype,ALLEGRO_BITMAP*& b,int seq, float a, float m,float e);
void createexplosion(int ttype,float x,float y);
void drawexplosions(ALLEGRO_BITMAP* screen);
void gettype(explosion_type& a,ALLEGRO_BITMAP*& b,int& nseq, float& aa, float& ee, float& mm);
};#endif
explosionhandler.cpp:
explosionhandler::explosionhandler()
{
num_types=0;
}
void explosionhandler::registerexplosion(int& ttype,ALLEGRO_BITMAP*& b,int seq, float a, float m,float e)
{
explosion_type n;
....
ttype = num_types; /*********** right here *******************/
num_types++;
type.push_back(n);
}
explosionhandler passed as pointer to object rocket:
rocket.h:
...
class explosionhandler;
class rocket {
public:
...
void setrocket(ALLEGRO_BITMAP*& a,ALLEGRO_BITMAP*& b, explosionhandler*& h);
...
int exptype;
...
}; #endif
rocket.cpp:
rocket::rocket()
{
...
exptype=-1;
}
void rocket::setrocket(ALLEGRO_BITMAP*& a,ALLEGRO_BITMAP*& b, explosionhandler*& h)
{
handler = h;
area.sethitboundaries(a);
fprintf(stdout,"setrocket, # of rockets in vector: %i\n",(int)rockets.size());
h->registerexplosion(exptype,b,3,(float)al_get_bitmap_width(b),(float)0,(float)-18); //called function
}
and finally main.cpp (abbreviated):
#include "rocket.h"
#include "explosionhandler.h"
#include <allegro5/allegro.h>
#include <allegro5/allegro_image.h>
#include <stdio.h>
#include <cstdlib>
#define PI 3.14159265
...
rocket rock(bullet_speed+2,width,height);
explosionhandler *handler;
...
int setup()
{
...
rock.setrocket(rk,exp,handler);
rock.setlimit(5);
al_set_target_bitmap(al_get_backbuffer(display));
...
}
...
Ok Yeah its clear now the problem was handler was not initialized. whoops.
and of course explosionhandler is a pointer in main.cpp, rocket is an object declared in main.cpp, both are globals.
Bless my little noob heart I know not what I do.
My psychic sense tells me that you're calling rocket::setrocket with a NULL pointer as the parameter h (or more specifically, a reference to a NULL pointer), and then you're calling h->registerexplosion() on the NULL pointer.
Don't do that. Pass in a valid pointer instead, or allocate a new object (making sure you delete it properly later).