I have two classes:
class CEnemy : CObject
{
protected:
int hitPoints;
};
class COgro : public CEnemy
{
COgro::COgro() {hitPoints = 100}
};
and in other file I have class 'CRocket', which can collide with COgro, there is it function:
void CRocket::OnCollision(CObject *collisionObject)
{
if (typeid(*collisionObject) == typeid(COgro))
{
//collisionObject->hitPoints -= 10; ?? or what?
}
}
I want to shoot 10 times to ogro before it dies. How to do this?
I've already tried:
collisionObject->hitPoints -= 10;
(CEnemy)collisionObject->hitPoints -= 10;
but I can't compile it...how to edit this hitPoints value, but without changing '(CObject *collisionObject)'?
Thx
EDIT:
//===============================================================
//------------------------------------CLASS CRocket-----------------------
class CRocket : public CObject
{
protected:
void OnAnimate(scalar_t deltaTime);
void OnCollision(CObject *collisionObject);
void OnDraw(CCamera *camera);
public:
float pitch;
float distanceTravel;
CVector forward;
bool isExplosion;
CTexture *explosionTex;
CExplosion *explosion;
CRocket();
~CRocket();
void Load();
void Unload();
};
void CRocket::OnCollision(CObject *collisionObject)
{
if (typeid(*collisionObject) == typeid(COgroEnemy))
{
isExplosion = true;
velocity = CVector(0.0, 0.0, 0.0);
explosion = new CExplosion(500, position, 8.0, explosionTex->texID);
PlaySound();
}
}
//-----------------------------------------class CObject
class CObject : public CNode
{
protected:
virtual void OnAnimate(scalar_t deltaTime)
{
position += velocity * deltaTime;
velocity += acceleration * deltaTime;
}
virtual void OnDraw(CCamera *camera) {}
virtual void OnCollision(CObject *collisionObject) {}
virtual void OnPrepare()
{
ProcessCollisions(FindRoot());
}
public:
CVector position;
CVector velocity;
CVector acceleration;
scalar_t size;
bool isDead;
CObject() {isDead = false;}
~CObject() {}
...
...
...
}
//---------------------------------------class CEnemy
class CEnemy : public CObject
{
public:
int hitPoints;
protected:
float distFromPlayer;
float runSpeed;
AIState_t aiState;
virtual void OnProcessAI() {}
void OnCollision(CObject *collisionObject)
{
// if this enemy collides with another enemy
if (typeid(*collisionObject) == typeid(CEnemy))
{
modelState = MODEL_IDLE;
velocity = CVector(0.0, 0.0, 0.0);
}
// if this enemy collides with the terrain (always)
else if (typeid(*collisionObject) == typeid(CTerrain))
{
position.y = ((CTerrain*)collisionObject)->GetHeight(position.x, position.z) + size;
}
else
{
}
}
public:
CPlayer *player;
...
...
//----------------------------------class COgro-------------------------
class COgroEnemy : public CEnemy
{
protected:
void OnProcessAI();
void OnCollision(CObject *collisionObject);
void OnPrepare();
public:
COgroEnemy() { Load(); }
COgroEnemy(float x, float z) { position.x = x; position.z = z; Load(); }
~COgroEnemy() {}
void Load();
};
You'll need to cast the pointer to a pointer type CEnemy* (or a subclass), or the dereferenced pointer to a reference type CEnemy&. For maximum safety, I'd suggest dynamic_cast, rather than an evil C-style cast; although that's slightly paranoid since you're checking the type before casting.
// no checks, undefined behaviour if type is wrong
((CEnemy*)collisionObject)->hitPoints -= 10;
static_cast<CEnemy*>(collisionObject)->hitPoints -= 10;
// throws if type is wrong
dynamic_cast<CEnemy&>(*collisionObject).hitPoints -= 10;
// does nothing if type is wrong
if (CEnemy* enemy = dynamic_cast<CEnemy*>(collisionObject)) {
enemy->hitPoints -= 10;
}
You might combine that with the type check, rather than using typeid:
if (COgro * ogro = dynamic_cast<COgro*>(collisionObject)) {
ogro->hitPoints -= 10;
}
Note that this isn't exactly the same as your test: it will pass if the object is a subtype of COgro, while your test checks for an exact match.
You code is not compiling because you are trying to access a class's protected data member from an external source.
The collisionObject parameter is an instance of CObject, which does not have a hitPoints data member.
Also, when you pass around pointers to base classes to functions, the functions should assume that they can only access the interface or features of the base class.
You should write another overloaded method:
void CRocket::OnCollision(CEnemy& enemy);
Or move the hitPoints data member to the CObject class.
Related
I am getting a compiler error saying that the data member Point p is private within the context, when I declare Point p as private within class circle. The code and compiler error are below.
#include<iostream>
#include<vector>
class Point
{
public:
Point(double a, double b)
{
x = a;
y = b;
}
virtual ~Point(){}
private:
double x;
double y;
};
The code for the class shape and circle are as follows:
class shapes {
public:
virtual Point centre() const = 0;
virtual void draw() const = 0;
virtual void rotate(int angle) const = 0;
virtual ~shapes(){}
};
class circle: public shapes {
public:
Point centre() const override { return p; }
void draw() const override { }
void rotate(int angle) const override {}
virtual ~circle() {}
circle(Point x, int r):p{x},radius{r}{}
private:
Point p;
int radius; };
Edit: Smiley face class inherits from circle class with code below:
class smiley: public circle
{ //smiley face is a circle + eyes and mouth
public:
smiley(Point p, int r):circle{p,r},mouth{nullptr}{}
Point centre() const override { return p;}
void draw() const override
{
//draw circle
circle::draw();
for(auto e:eyes)
{
e->draw();
}
mouth->draw();
}
void rotate(int angle) const {}
virtual ~smiley()
{
delete mouth;
for (auto eye : eyes) //why not delete [] eyes
{
delete eye;
}
}
private:
std::vector<shapes*> eyes; //smiley face has eyes
shapes* mouth; //smiley face has a mouth
};
If I make the data member p public in the class circle, everything works. The compiler error is listed below:
Why can I not define the Point object p, in the circle class private?
Edit: I have added the compiler error message and added the missing code asked for in the comments below. Would you be able to re-open the question?
Private class members can only be accessed within the class or by friends, so, if you would like it to be accessed outside the class by a non-friend, you would need to use a setter/getter.
Is it possible to achieve behaviour demonstrated below with virtual functions? And if it's not the correct way to go about polymorphism then what would be the correct way in this example?
class Base_
{
float x;
float y;
float z;
public:
Base_(float xx=0, float yy=0, float zz=0)
{
x = xx;
y = yy;
z = zz;
}
virtual void SetParemeters(what here?)=0; //Different number of arguments
};
class Derived_1 :public Base_
{
float r;
public:
Derived_1(float rr=1, float xx=0, float yy=0, float zz=0):Base_(xx,yy,zz)
{
r=rr;
}
virtual void SetParemeters(float v1) //Different number of arguments
{
r=v1;
}
};
class Derived_2 :public Base_
{
float k;
float w;
public:
Derived_2(float kk=1, float ww=1,float xx=0, float yy=0, float zz=0):Base_(xx,yy,zz)
{
k=kk;
w=ww;
}
virtual void SetParemeters(float v1, float v2) //Different number of arguments
{
k=v1;
w=v2;
}
};
int main()
{
Derived_1 d1;
Derived_2 d2;
Base_ *ptr;
ptr = &d1;
ptr -> SetParemeters(one argument)
ptr = &d2;
ptr-> SetParemeters(one or two arguments)
return 0;
}
And even if I managed to achieve that, how can I set only second parameter (k) here: ptr-> SetParemeters(one or two arguments)?
I searched for answers but I only found answers to specific scenarios which made the whole thing difficult for me to understand.
Yes, make Base_::SetParameters takes two (optional) arguments:
class Base_
{
// [...]
public:
virtual void SetParemeters(float=0f, float=0f)=0;
};
Derived_1::SetParameters just ignores the first one:
class Derived_1 :public Base_
{
// [...]
virtual void SetParemeters(float v1, float=0f)
{
r=v1;
}
};
while Derived_2 takes the both of them
class Derived_2 :public Base_
{
// [...]
virtual void SetParemeters(float v1, float v2)
{
k=v1;
w=v2;
}
};
demo: https://coliru.stacked-crooked.com/a/c528ffff005df5b9
Note though, this significantly reduces the interest of virtual functions...
Derived_1 d1;
Derived_2 d2;
Base_ *ptr;
ptr = &d1;
ptr->SetParameters(one argument)
ptr = &d2;
ptr->SetParameters(one or two arguments)
The way how this code is written implies that you have knowledge about two things:
at the time of the first call to SetParameters(), ptr points to an object of type Derived_1
at the second call, it points to an object of type Derived_2.
This in turn means that you know the static types -- and in fact, you need to, due to the different signatures.
For such a scenario, dynamic polymorphism is not the right choice, because its premise is that you can talk to different implementations (overridden methods) using a uniform access (calling the virtual base method).
So, if you have this knowledge at compile time, simply use non-virtual method calls.
However, there are similar scenarios where you may actually be interested in supporting different signatures at runtime, for example if you load configuration dynamically. Here is an example, where not the number, but the types of arguments differ.
class Car : public Vehicle
{
virtual void addFuel(const Petrol& f) override;
};
class Airplane : public Vehicle
{
virtual void addFuel(const Kerosene& f) override;
};
How would then the base function look?
class Vehicle
{
virtual ~Vehicle() {} // don't forget this!
virtual void addFuel(const /* which type? */& f) = 0;
};
One option is to make the fuel type a hierarchy as well (both Kerosene and Petrol inherit the Fuel class):
class Vehicle
{
virtual ~Vehicle() {}
virtual void addFuel(const Fuel& f) = 0;
};
However, in this case, each implementation would need to either rely on the fact it's passed the right fuel, or check the type at runtime.
class Airplane : public Vehicle
{
virtual void addFuel(const Fuel& f) override
{
if (auto* k = dynamic_cast<const Kerosene*>(&f))
{
// use concrete fuel
}
}
};
You can make SetParameters a variadic function and have the polymorphic interface be internal, providing the writeable parameters in a generic form (here as a vector of pointers to them):
class Base_
{
float x;
float y;
float z;
public:
Base_(float xx=0, float yy=0, float zz=0)
{
x = xx;
y = yy;
z = zz;
}
virtual std::vector<float*> getAllExtraParameters() = 0;
template<class ... Ts>
void SetExtraParameters(Ts&& ... ts)
{
auto extras = getAllExtraParameters();
if (sizeof...(ts) > extras.size())
throw std::runtime_error("Too many parameters given!");
// Fold expression - could be implemented differently in C++ < 17.
int index = 0;
((*extras[index++] = ts), ...);
}
};
class Derived_1 :public Base_
{
float r;
public:
Derived_1(float rr=1, float xx=0, float yy=0, float zz=0):Base_(xx,yy,zz)
{
r=rr;
}
std::vector<float*> getAllExtraParameters() override
{
return { &r };
}
};
class Derived_2 :public Base_
{
public:
float k;
float w;
Derived_2(float kk=1, float ww=1,float xx=0, float yy=0, float zz=0):Base_(xx,yy,zz)
{
k=kk;
w=ww;
}
std::vector<float*> getAllExtraParameters() override
{
return { &k, &w };
}
};
Demo and tests: https://godbolt.org/z/ofXnuH
The function "foo" is from external library (In my case DEAlII ).
It takes in class type as template parameter and its object. It then creates a copy of this object and performs some operation on this object.
The problem is when the input class is polymorphic (template ). Then I always pass base class object but pointing to different derived class, but the copied object in the function "foo" will be base class.
And any call to member function on this copied object will call base class member function(But I need them to call to corresponding derived class member function).
Additionally the type of derived class is decided at runtime based on some input parameter. I cannot change/ move to different library, but I should be able to modify the function "foo" in the library(preferably not but may be as a last resort).
#include <iostream>
#include <memory>
using namespace std;
class Shape {
protected:
int width, height;
public:
Shape( int a = 0, int b = 0){
width = a;
height = b;
}
void set(int a){
width =a ;
}
virtual int area() {
cout << "Parent class area :" <<endl;
return 0;
}
virtual ~Shape()=default;
};
class Rectangle: public Shape {
public:
Rectangle( int a = 0, int b = 0):Shape(a, b) { }
int area () override{
cout << "Rectangle class area :" <<width*height <<endl;
return (width * height);
}
};
class Triangle: public Shape {
public:
Triangle( int a = 0, int b = 0):Shape(a, b) { }
int area () {
cout << "Triangle class area :" <<endl;
return (width * height / 2);
}
Triangle(const Triangle &triangle){
width = triangle.width;
height = triangle.height;
}
};
template <class temp>
void foo (temp &shape){
shape.area();
temp shape_sample = shape;
shape_sample.area();
}
// Main function for the program
int main() {
unique_ptr<Shape> shape;
Rectangle rec(10,7);
shape =make_unique<Rectangle> (rec);
foo (*shape.get());
shape->area();
return 0;
}
If the implementation of foo can't be change then I see two options here:
Option 1: Simply downcast to appropriate type if you know what it is:
foo(static_cast<Rectangle &>(*shape.get()));
Option 2 (overkill): hide the polymorphism using Bridge pattern:
class Shape {
protected:
class ShapeImpl {
public:
int width, height;
virtual ~ShapeImpl() = default;
// "virtual copy constructor" which you could've used without a Bridge
// if you could change "foo"
virtual ShapeImpl *clone() { return new ShapeImpl(*this); }
virtual int area() {
cout << "Parent class area :" <<endl;
return 0;
}
} *impl; // can't use unique_ptr because we want copy
Shape(ShapeImpl *impl)
: impl(impl) { }
public:
Shape(const Shape &other)
: impl(other.impl ? other.impl->clone() : nullptr) {
}
Shape(Shape &&other)
: impl(nullptr) {
std::swap(impl, other.impl);
}
virtual ~Shape() {
delete impl;
}
// copy-and-swap idiom with one assignment operator to "rule-of-five them all"
Shape &operator=(Shape other) {
std::swap(impl, other.impl);
return *this;
}
int area() {
return impl->area();
}
};
class Rectangle : public Shape {
protected:
class RectangleImpl : public ShapeImpl {
public:
ShapeImpl *clone() override { return new RectangleImpl(*this); }
int area() override {
cout << "Rectangle class area :" <<width*height <<endl;
return (width * height);
}
};
public:
Rectangle(int width = 0, int height = 0)
: Shape(new RectangleImpl())
{
impl->width = width;
impl->height = height;
}
};
If the implementation of the foo could not be changed. one other option is to write a wrapper around it and using dynamic cast send the right type to it.
template <class temp>
void foo (temp &shape)
{
shape.area();
temp shape_sample = shape;
shape_sample.area();
}
void fooWrapper(Shape* shape)
{
Rectangle* shape1 = dynamic_cast<Rectangle*>(shape);
if (shape1)
{
foo<Rectangle>(*shape1);
return;
}
Triangle* shape2 = dynamic_cast<Triangle*>(shape);
if(shape2)
{
foo<Triangle>(*shape2);
return;
}
shape->area();
return;
}
// Main function for the program
int main() {
unique_ptr<Shape> shape;
Triangle tri(10,7);
shape =make_unique<Triangle> (tri);
fooWrapper(shape.get());
Rectangle rec(10,7);
shape = make_unique<Rectangle> (rec);
fooWrapper(shape.get());
return 0;
}`
Someone recommended me to use boost::variant as shape variable to store different types of shapes in it. But, when implemented boost::variant to my code, I got an error while compiling. Error says: 'Shape': base class undefined and more errors.
Here is my code (Object.h):
using Shape = boost::variant<Rectangle, Circle>;
enum Shape_Type
{
RECTANGLE,
CIRCLE
};
struct Position
{
float x, y;
Position(float position_x, float position_y)
{
x = position_x;
y = position_y;
}
};
class Object : private Shape
{
private:
std::string name;
public:
Object() = default;
Object(std::string name, Rectangle rectangle) : name(name), Shape(rectangle)
{
}
Object(std::string name, Circle circle) : name(name), Shape(circle)
{
}
void setPosition(float, float);
void setAngle(float);
Shape* getShape()
{
Shape* shape = this;
return shape;
}
Position getPosition();
const std::string* getName()
{
return &name;
}
};
class Rectangle
{
private:
sf::RectangleShape rectangleshape;
public:
Rectangle() = default;
Rectangle(float width, float height)
: rectangleshape(sf::RectangleShape(sf::Vector2f(width, height)))
{
}
void setPosition(float position_x, float position_y)
{
rectangleshape.setPosition(position_x, position_y);
}
void setAngle(float angle)
{
rectangleshape.setRotation(angle);
}
sf::RectangleShape* getRectangleShape()
{
return &rectangleshape;
}
Position getPosition()
{
return Position(rectangleshape.getPosition().x,
rectangleshape.getPosition().y);
}
};
class Circle
{
private:
sf::CircleShape circleshape;
public:
Circle() = default;
Circle(std::string name, float radius)
: circleshape(sf::CircleShape(radius))
{
}
void setPosition(float position_x, float position_y)
{
circleshape.setPosition(position_x, position_y);
}
void setAngle(float angle)
{
circleshape.setRotation(angle);
}
sf::CircleShape* getCircleShape()
{
return &circleshape;
}
Position getPosition()
{
return Position(circleshape.getPosition().x,
circleshape.getPosition().y);
}
};
And btw is getShape() function good?
Variants are used for static polymorphism, so you don't need the base class at all (that's dynamic - or virtual - polymorphism).
The members in a variant typically do not share a common base class, so you wouldn't have the getShape function, or you'd need to template it:
template <typename T>
T const& getShape() const { return boost::get<T>(_shape); }
I am defining a class GameState and a class MainMenuGameState. The former is meant to be an abstract class and the latter is inheriting it. But somehow, I am not able to overwrite its properties.
GameState.h
#ifndef _GAME_STATE_H_
#define _GAME_STATE_H_
#include <SDL2/SDL.h>
class GameState {
public:
virtual void loop(Uint32 deltaTime) = 0;
virtual void render() = 0;
virtual void event(SDL_Event * event) = 0;
bool stopRenderPropagation = false;
bool stopLoopPropagation = false;
};
#endif
MainMenuGameState.h
#ifndef _MAIN_MENU_GAME_STATE_H_
#define _MAIN_MENU_GAME_STATE_H_
#include "../Game.h"
class MainMenuGameState : public GameState {
public:
MainMenuGameState(Game * pGame);
void loop(Uint32 deltaTime);
void render();
void event(SDL_Event * event);
bool stopRenderPropagation = true;
bool stopLoopPropagation = true;
private:
Game * game;
int xOffset = 0;
int yOffset = 0;
};
#endif
So after instanciating a MainMenuGameState object, I expected stopRenderPropagation and stopLoopPropagation to be true, but they are false.
I also had no luck overwriting them inside the constructor for some reason.
MainMenuGameState::MainMenuGameState(Game * pGame) {
game = pGame;
xOffset = rand() % 20;
yOffset = rand() % 20;
stopRenderPropagation = true;
stopLoopPropagation = true;
}
After that, they are still true. I don't know weather this is a problem with my constructor or if I misunderstood polymorphism in c++.
The instances of MainMenuGameState get stored in a vector<GameState *>, could this be the problem? I am accessing the properties like this:
if(gameStates.begin() != gameStates.end()) {
std::vector<GameState *>::iterator it = gameStates.end();
do {
--it;
} while(it != gameStates.begin() && (*it)->stopLoopPropagation == false);
while(it != gameStates.end()) {
(*it)->loop(deltaTime);
++it;
}
}
Thank you for your help!
Your derived class is declaring another couple of members with the same name of the members in the base class, thus "hiding" the base ones.
You should accept the initial values for those members in the constructor, or if they are fixed properties of the class that never change you should make them member functions instead like in
class GameState {
public:
...
virtual bool stopRenderPropagation() { return false; }
virtual bool stopLoopPropagation() { return false; }
};
class MainMenuGameState : public GameState {
public:
...
bool stopRenderPropagation() { return true; }
bool stopLoopPropagation() { return true; }
...
};
Inheriting data members (your booleans) does not work in the same way as inheriting and overloading methods. Try putting the bools as protected inherited data members instead (uninitialized), and initialize them in the respective subclass constructors instead.
class MainMenuGameState : public GameState {
public:
MainMenuGameState(Game * pGame);
void loop(Uint32 deltaTime);
void render();
void event(SDL_Event * event);
protected:
bool stopRenderPropagation;
bool stopLoopPropagation;
private:
Game * game;
int xOffset = 0;
int yOffset = 0;
};
You declare new variables in your derived class, which is leading to these problems. Variables that are not private are inherited:
struct A { int x };
struct B : A {}; // has B::x by inheritance
You can just set them in your constructor without redeclaration:
struct A { int x; };
struct B : A { B() : x(1) {} };
Notice that it is usually considered bad practice to declare public variables, it is more common to implement getters and setters instead:
struct A
{
int x() const { return x_; }
int & x() { return x_; }
private:
int x_;
};