Invalid conversion c++ - 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.

Related

Use of deleted Function when pushing class object to std::vector?

I have two classes as shown below.
When i try to populate a vector of Entity objects in the Spawner Entity class,it gives me this error
error: use of deleted function 'Entity::Entity(Entity&&)'
I cant figure out why it wont call the constructor and push the class object on the vector
Also, I Have inherited the Entity Class in the Spawner Entity
Entity.h
#pragma once
#include<iostream>
#include<vector>
#include<SFML/Window.hpp>
#include<SFML/Graphics.hpp>
class Entity
{
private:
sf::RenderWindow win;
sf::RectangleShape enemy;
public:
Entity();
void InitializeEntity();
void Update(const float* DeltaTime);
void Render(sf::RenderWindow& mWindow);
};
Entity.cpp
Entity::Entity()
{
InitializeEntity();
}
void Entity::InitializeEntity()
{
enemy.setPosition(rand()%255+1,rand()%255+1);
enemy.move(rand()%255+1,rand()%255+1);
enemy.setSize(sf::Vector2f(50.f,50.f));
sf::Color color(rand()%255+1,rand()%255+1,rand()%255+1);
enemy.setFillColor(color);
enemy.setOutlineColor(sf::Color::White);
enemy.setOutlineThickness(2.f);
}
void Entity::Render(sf::RenderWindow& mWindow)
{
mWindow.draw(enemy);
}
SpawnerEntity.h
#pragma once
#include<iostream>
#include<vector>
#include<SFML/Window.hpp>
#include<SFML/Graphics.hpp>
#include "Entity.h"
class SpawnerEntity:public Entity
{
private:
float SpawnTimer;
float SpawnTimerMax;
int MaxEnemies;
bool done;
//std::vector<Entity> SpawnedEnemies;
public:
SpawnerEntity();
void InitializeEntity();
void SpawnSubEntities(std::vector<Entity> &enemies);
bool CheckSpawnDone();
};
SpawnerEntity.cpp
#include "SpawnerEntity.h"
SpawnerEntity::SpawnerEntity()
{
SpawnTimerMax=1.f;
SpawnTimer=SpawnTimerMax;
MaxEnemies=10;
done=false;
}
bool SpawnerEntity::CheckSpawnDone()
{
return done;
}
void SpawnerEntity::SpawnSubEntities(std::vector<Entity> &enemies)
{
for(int i=0;i<MaxEnemies;i++)
{
std::cout << "SPAWNED" << '\n';
enemies.push_back(Entity()); //this line here gives me the above error
}
done=true;
}

c++ [gamestate] function does not take in correct argument error

Hello i have problem of compile my code
i follow http://gamedevgeek.com/tutorials/managing-game-states-in-c/ tutorial
but it fail to compile and i don't know why.
the error msg from visual studio
here is my code
the CGameEngine modify code
#include <vector>
#include "GameState.h"
#include "GameEngine.h"
class GameState;
class GameStateManager
{
public:
GameStateManager(GameEngine* engine, MSG * msg);
~GameStateManager();
void Cleanup();
void ChangeState(GameState* state);
void Update();
bool Running() { return m_running; }
void Quit();
private:
std::vector<GameState *> states;
bool m_running;
GameEngine * m_engine;
MSG *m_msg;
};
#include "GameStateManager.h"
GameStateManager::GameStateManager(GameEngine* engine, MSG * msg)
:m_engine{ engine }, m_msg{ msg }, m_running{ true }
{
}
GameStateManager::~GameStateManager()
{
}
void GameStateManager::Cleanup()
{
while (!states.empty()) {
states.back()->Exit();
states.pop_back();
}
}
void GameStateManager::Quit()
{
m_running = false;
m_msg->message = WM_QUIT;
}
void GameStateManager::ChangeState(GameState* state)
{
if (!states.empty()) {
states.back()->Exit();
states.pop_back();
}
states.push_back(state);
states.back()->Enter(m_engine, m_msg);
}
void GameStateManager::Update()
{
states.back()->Update(this);
}
the CGameState modify code
#include "GameStateManager.h"
class GameState
{
public:
GameState() {}
virtual ~GameState() {}
virtual void Enter(GameEngine * , MSG * ) = 0;
virtual void Update(GameStateManager* game) =0;
virtual void Exit() = 0;
};
one of the state class
#include "MainMenu.h"
class Logo :public GameState
{
public:
Logo();
~Logo();
static Logo* Instance()
{
return &m_Logo;
}
void Enter(GameEngine * engine, MSG * msg);
void Update(GameStateManager* game);
void Exit();
private:
static Logo m_Logo;
};
#include "Logo.h"
Logo::Logo()
{
}
Logo::~Logo()
{
}
void Logo::Enter(GameEngine * engine, MSG * msg)
{
m_GameEngine_Info = engine;
m_msg = msg;
}
void Logo::Update(GameStateManager* game)
{
}
void Logo::Exit()
{
}
i get no compile error when editing the code, but when i try compile it get this error.
You have circular includes. Use include guards and replace
#include "GameStateManager.h"
with
class GameStateManager;
in GameState.h. Move this include into GameState.cpp.
Do similar with #include "GameEngine.h" and #include "GameState.h" in GameStateManager.h and GameStateManager.cpp.

Handling collisions with objects that use vector of unique pointers

#pragma once
#include "Entity.h"
#include <iostream>
class Projectile : public Entity
{
public:
Projectile() {}
Projectile(float x, float y) {
load("Graphics/Projectile.png");
m_sprite.setPosition(x, y);
m_speed = 400;
}
};
#pragma once
#include "Entity.h"
#include <iostream>
#include "Projectile.h"
enum class Color {
red,
yellow,
brown,
blue
};
class Enemy : public Entity
{
public:
Enemy(const Color& c, const sf::Vector2f& pos) {
switch (c) {
case Color::blue:
{
load("Graphics/blueEnemy.png");
}
break;
case Color::red:
{
load("Graphics/redEnemy.png");
}
break;
case Color::yellow:
{
load("Graphics/yellowEnemy.png");
}
break;
case Color::brown:
{
load("Graphics/brownEnemy.png");
}
break;
}
setPos(pos);
m_speed = 100;
}
};
#pragma once
#include "Entity.h"
#include "Projectile.h"
#include <vector>
class Spaceship : public Entity
{
public:
Spaceship();
void move(float);
void shoot(float);
void update(float);
void draw(sf::RenderWindow*) override;
private:
bool wasSpacePressed;
std::vector<std::unique_ptr<Projectile>> m_projectiles;
sf::Clock m_clock;
};
class EnemyFleet : public Entity
{
public:
EnemyFleet();
~EnemyFleet();
void move(float);
bool isEnemyBottom() const;
bool isLeftMost() const;
bool isRightMost() const;
void moveX(float);
void moveDown();
void update(float);
void draw(sf::RenderWindow*) override;
private:
std::vector<std::unique_ptr<Enemy>> m_enemyFleet;
bool m_leftToRight; //motion of the enemyfleet
float m_speedModifier;
};
I want to be able to delete a projectile and enemy when they collide with each other, but I'm not sure how to do this since unique_ptr cannot be copied into any parameter in some collision manager class bc it has exclusive ownership. Is unique_ptr still something i should use bc i dont have to call delete (like if its a raw ptr)?
Yes, you can't copy unique_ptr, but you can copy or get reference from object that unique_ptr points to (Projectile and Enemy).
//Example
bool collision_manager::is_collision(Projectile & pr, Enemy & en) {
if (pr.position() == en.position()) {
return true;
}
return false
}
// similar for other objects that contain vector of unique_ptr
Projectile & Spaceship::get_Projectile(size_t num) {
if(num < m_projectiles.length()) {
return *projectiles.at(num);
}
throw std::invalid_argument("some alert info");
}
Instead of copying you can also use std::move(unique_ptr...).

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

Object is wrong type

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).