Reputation: 125
I seem to have a problem when I am trying to inherit my sf::Sprite and sf::Texture from my base class to my subclass. It kind of works when I try to send the sprite and texture as an copy, but I will of course not get any image then. Do you have any idea how I can fix this problem? My base class:
#ifndef OBJECTHOLDER_H
#define OBJECTHOLDER_H
#include <SFML\Graphics.hpp>
using namespace std;
class ObjectHolder : public sf::Drawable {
private:
float windowHeight;
float windowWidth;
sf::Texture texture;
sf::Sprite sprite;
public:
ObjectHolder();
virtual ~ObjectHolder();
float getWindowHeight() const;
float getWindowWidth() const;
const sf::Sprite & getSprite() const;
const sf::Texture & getTexture() const;
};
#endif //OBJECTHOLDER_H
#include "ObjectHolder.h"
ObjectHolder::ObjectHolder() {
float windowHeight;
float windowWidth;
}
ObjectHolder::~ObjectHolder() {
}
float ObjectHolder::getWindowHeight() const {
return this->windowHeight;
}
float ObjectHolder::getWindowWidth() const {
return this->windowWidth;
}
const sf::Sprite & ObjectHolder::getSprite() const {
return this->sprite;
}
const sf::Texture & ObjectHolder::getTexture() const {
return this->texture;
}
My subclass:
#ifndef PROJECTILE_H
#define PROJECTILE_H
#include "ObjectHolder.h"
class Projectile : public ObjectHolder {
public:
Projectile();
virtual ~Projectile();
void move(const sf::Vector2f& amount);
virtual void draw(sf::RenderTarget &target, sf::RenderStates states) const;
};
#endif //PROJECTILE_H
#include "Projectile.h"
#include <iostream>
Projectile::Projectile() {
if (!this->getTexture().loadFromFile("../Resources/projectile.png")) {
cout << "Error! Projectile sprite could not be loaded!" << endl;
}
this->getSprite().setTexture(getTexture());
this->getSprite().setPosition(sf::Vector2f(940.0f, 965.0f));
}
Projectile::~Projectile() {
}
void Projectile::move(const sf::Vector2f & amount) {
this->getSprite().move(amount);
}
void Projectile::draw(sf::RenderTarget & target, sf::RenderStates states) const{
target.draw(this->getSprite(), states);
}
Upvotes: 0
Views: 867
Reputation: 36527
You can just mark those members as protected
rather than private
, which allows your derived classes to access them directly:
class Base {
protected:
sf::Texture m_Texture;
}
class Derived : public Base {
Derived() {
m_Texture.loadFromFile("myTexture.png");
}
}
Upvotes: 2