Pong game bugging out - mayby pointer to class [closed] - c++

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
get a problem with my code, this is just an extract from a larger piece of code involving OpenGL but still demonstrates the problem. It works without the collision detection call (col.detect()) - if you consider unbouncy walls working - but when I uncomment it the program breaks. Nothing seems to be wrong with the code itself it compiles just fine but doesn't work the way that I am expecting.
Thanks for all the help
Best Regards
collision.h
#pragma once
#include "Ball.h"
class collision
{
public:
collision();
collision(Ball ball);
void detect();
~collision();
private:
Ball *point;
};
Ball.h
#pragma once
class Ball
{
public:
Ball();
double getpx();
double getpy();
double getvx();
double getvy();
void setpx(const double px);
void setpy(const double py);
void setvx(const double vx);
void setvy(const double vy);
void update();
~Ball();
private:
double position[2] = { 0, 0 };
double velocity[2] = { 0.1, 0 };
};
collision.cpp
#include "collision.h"
collision::collision()
{
}
collision::collision(Ball ball)
{
point = &ball;
}
void collision::detect()
{
if (point->getpx() > 1 || point->getpx() < -1)
point->setvx(-point->getvx());
else if (point->getpy() > 1 || point->getpy() < -1)
point->setvy(-point->getvy());
}
collision::~collision()
{
}
Ball.cpp
#include "Ball.h"
Ball::Ball()
{
}
double Ball::getpx()
{
return position[0];
}
double Ball::getpy()
{
return position[1];
}
double Ball::getvx()
{
return velocity[0];
}
double Ball::getvy()
{
return velocity[1];
}
void Ball::setpx(const double px)
{
position[0] = px;
}
void Ball::setpy(const double py)
{
position[1] = py;
}
void Ball::setvx(const double vx)
{
velocity[0] = vx;
}
void Ball::setvy(const double vy)
{
velocity[1] = vy;
}
void Ball::update()
{
position[0] += velocity[0];
position[1] += velocity[1];
}
Ball::~Ball()
{
}
main.cpp
#include <iostream>
#include "Ball.h"
#include "collision.h"
using namespace std;
int main()
{
Ball tennis;
collision col(tennis);
while (true)
{
tennis.update();
col.detect();
cout << tennis.getpx() << endl;
cin.get();
}
return 0;
}

Below will cause your program to invoke Undefined Behavior when next you use point:
collision::collision(Ball ball)
{
point = &ball;
}
Where point is defined to be:
Ball *point;
The problem is that you are storing the address of an object with automatic storage-duration. ball will cease to exist after that function completes hence leaving point to point ot an invalid object.
You probably wanted to take the ball by reference; or better still use the services of std::unique_ptr or std::shared_ptr in your program.

Change the following code
collision::collision(Ball ball)
to
collision::collision(Ball& ball)
It should solve your problem. The problem was that Ball was a local variable whose address is no longer valid after the constructor exits. Solution : Send the object by reference and the address stored in the pointer will be of the object created in the main() function.

Related

OOP in C++ newbie [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 days ago.
Improve this question
I'm a newcomer in C++ OOP and I try to do assignment from my prof.
The prof asked me to create a program that prompt the users to input the number of vertex of a polygon and also its vertices in 2D. That's all.
For example:
Number of points: 3
Enter vertex 1 coordinate: 1 1
Enter vertex 2 coordinate: 1 2
...
I have tried to create 5 files: Point2D.cpp; Point2D.h; Polygon.cpp; Polygon.h and main.cpp
Point2D.cpp
#include "Point2D.h"
#include <iostream>
using namespace std;
Point2D::Point2D(float newX, float newY) {
cout << "calling float type" << endl;
}
void Point2D::setX(float val) {
x = val;
}
float Point2D::getX() {
return x;
}
void Point2D::setY(float val) {
y = val;
}
float Point2D::getX() {
return y;
}
Point2D.h
#pragma once
class Point2D {
private:
float x, y;
public:
// constructor with parameter + default
Point2D(float newX = 0, float newY = 0);
void setX(float val);
float getX();
void setY(float val);
float getY();
};
Polygon.cpp
#include "Polygon.h"
#include <iostream>
Polygon::Polygon() {
verticesCount = 0;
verticesList = NULL;
}
Polygon::Polygon(int vCount) {
if (vCount > 0) {
verticesCount = vCount;
// allocate memory for verticesList
if (verticesList != NULL)
delete[] verticesList;
verticesList = new Point2D[verticesCount];
}
}
Point2D Polygon::getVertex(int index) {
if (verticesCount <= 0) {
return NULL;
} if (verticesList = NULL) {
return NULL;
} if (index >= verticesCount) {
return NULL;
}
return verticesList[index];
}
Polygon::~Polygon() {
}
Polygon.h
#pragma once
#include "Point2D.h"
class Polygon {
private:
Point2D* verticesList;
int verticesCount;
public:
Polygon();
Polygon(int vCount);
~Polygon();
Point2D getVertex(int index);
void addPoint(Point2D p);
};
main.cpp
#include <iostream>
#include "Point2D.h"
#include "Polygon.h"
using namespace std;
int main() {
// using default constructor
Point2D p = Point2D();
return 0;
}
I want to ask from you guys that if my code is correct or not. And what should I do next from there?
Thanks in advance!

Why does the compiler report such an error?('width' was not declared in this scope)

I am searching for a long time on net. But no use. Please help or try to give some ideas how to achieve this.
I've tried multiple variations of this, but none of them seem to work. Any ideas?
#include <iostream>
using namespace std;
class RectangleArea
{
public:
void SetData (float L,float W);
float ComputeArea();
void OutputArea();
private:
float length,width,area;
};
void RectangleArea::SetData(float L,float W)
{
length=L;
width=W;
}
float RectangleArea::ComputeArea()
{
area=length*width;
}
void RectangleArea::OutputArea()
{
cout<<"Area is "<<area<<endl;
}
int main()
{
RectangleArea Rectangle;
cout<<"input length and width:"<<endl; //The error appears in this position//
cin>>length>>width;
Rectangle.SetData(length, width);
Rectangle.ComputeArea();
Rectangle.OutputArea();
return 0;
}

Error: the program stops executing | Exit code: 255

Could you tell me where did I fail? the program close when executing.
Before, it can finish the execution, but it didn't show me the results I was expecting. That's before, now it closes and didn't show me the results.
For example: if I needed the result of discount, it shows me on the results a "nan", maybe there's the problem that didn't let it finish executing.
Now, as the title says, it didn't show me results but an exit code: 255.
However, if you go to an online compiler, paste the code, execute it and follow the instructions, you will see that at the end it doesn't show the results but an exit code: 139 Segmentation fault (core dumped)
I think the problem comes mainly from SalePrice(),
Maybe I wrote it wrong or I'm missing libraries, I don't have that knowledge yet.
Sorry if I did not explain myself well, I am still learning and this had not happened to me before.
Thanks for reading untill here!
#include <iostream>
#include <sstream>
#include <math.h>
using namespace std;
class CarOnSale
{
private:
string Brand;
string Country;
float Model;
float ImportationCost;
public:
//CONSTRUCTOR
CarOnSale(string, string, float, float);
//DESTRUCTOR
~CarOnSale();
//SETTERS
void setBrand(string);
void setCountry(string);
void setModel(float);
void setImportationCost(float);
//GETTERS
string getBrand();
string getCountry();
float getModel();
float getImportationCost();
//ATTRIBUTES
float Antiquity();
float Discount();
float Comission();
float Taxes();
float CompanyProfitPercentage();
float SalePrice();
float TotalPrice();
string toString();
};
//CONSTRUCTOR CONSTRUCTOR CONSTRUCTOR
CarOnSale::CarOnSale(string pBrand, string pCountry, float pModel, float pImportationCost)
{
Brand=pBrand;
Country=pCountry;
Model=pModel;
ImportationCost=pImportationCost;
}
//DESTRUCTOR DESTRUCTOR DESTRUCTOR
CarOnSale::~CarOnSale()
{
}
//SETTER SETTER SETTER SETTER SETTER
void CarOnSale::setBrand(string pBrand)
{
Brand=pBrand;
}
void CarOnSale::setCountry(string pCountry)
{
Country=pCountry;
}
void CarOnSale::setModel(float pModel)
{
Model=pModel;
}
void CarOnSale::setImportationCost(float pImportationCost)
{
ImportationCost=pImportationCost;
}
//GETTER GETTER GETTER GETTER GETTER
string CarOnSale::getBrand()
{
return(Brand);
}
string CarOnSale::getCountry()
{
return(Country);
}
float CarOnSale::getModel()
{
return(Model);
}
float CarOnSale::getImportationCost()
{
return(ImportationCost);
}
//ATTRIBUTES ATTRIBUTES ATTRIBUTES ATTRIBUTES
float CarOnSale::Antiquity()
{
float ActualYear=2019;
return ActualYear-Model;
}
float CarOnSale::Discount()
{
float Discount=0;
if(Antiquity()>10)
{
return Discount=SalePrice()*0;
}
else
{
if(Antiquity()<10&&Antiquity()>5)
{
return Discount=SalePrice()*0.05;
}
else
{
if(Antiquity()<5)
{
return Discount=SalePrice()*0.015;
}
}
}
}
float CarOnSale::Comission()
{
float Comission=0;
if(SalePrice()>8000000||Country=="USA"||Country=="Germany")
{
return Comission=ImportationCost*0.12;
}
else
{
return Comission=ImportationCost*0.06;
}
}
float CarOnSale::Taxes()
{
float Taxes=0;
if(Country=="Germany")
{
return Taxes=SalePrice()*0.2;
}
else
{
if(Country=="Japan")
{
return Taxes=SalePrice()*0.3;
}
else
{
if(Country=="Italy")
{
return Taxes=SalePrice()*0.15;
}
else
{
if(Country=="USA")
{
return Taxes=SalePrice()*0.08;
}
}
}
}
}
float CarOnSale::CompanyProfitPercentage()
{
float CompanyProfitPercentage=0;
return CompanyProfitPercentage=ImportationCost*0.3;
}
float CarOnSale::SalePrice()
{
float SalePrice=0;
return SalePrice=ImportationCost+CompanyProfitPercentage()-Comission()-Discount()-Taxes();
}
float CarOnSale::TotalPrice()
{
float TotalPrice=0;
return TotalPrice=ImportationCost+CompanyProfitPercentage()-Comission()-Discount()-Taxes();
}
string CarOnSale::toString()
{
stringstream s;
s<<"Car is "<<Antiquity()<<" years old"<<endl;
s<<"Discount: "<<Discount()<<" percent"<<endl;
s<<"Car's comission: "<<Comission()<<endl;
s<<"Car taxes: "<<Taxes()<<endl;
s<<"Company Profit Percentage: "<<CompanyProfitPercentage()<<endl;
s<<"Price of the car: "<<SalePrice()<<endl;
return s.str();
}
int main()
{
//Variables
string BrandMAIN, CountryMAIN;
float ModelMAIN, ImportationCostMAIN;
//Object
CarOnSale Car(BrandMAIN, CountryMAIN, ModelMAIN, ImportationCostMAIN);
//Actions
cout<<"Write your car's brand: "<<endl;
cin>>BrandMAIN;
cout<<"Write your car's country: "<<endl;
cin>>CountryMAIN;
cout<<"Write your car's model (year): "<<endl;
cin>>ModelMAIN;
cout<<"write your car's importation cost: "<<endl;
cin>>ImportationCostMAIN;
//SETTERS
Car.setBrand(BrandMAIN);
Car.setCountry(CountryMAIN);
Car.setModel(ModelMAIN);
Car.setImportationCost(ImportationCostMAIN);
//Prints
cout<<Car.toString();
return 0;
}
You've got a recursive condition that is causing your stack to overflow. Commision() calls SalePrice() which in turn calls Commision(), etc. on and on.
Refactor your functions so that they don't recursively call each other.

0xcdcdcdcd while using this->

Hi im doing little project tomy school and keep getting weird for me error.
While calling one of methods in my object this pointer is set to 0xcdcdcdcd. i googled it and found some info about erasing memory or destroing objects before calling, but i make sure no destructors are called before.
World.h
class Organism;
class Human;
class World
{
private:
vector <Organism*> organisms;
vector <Organism*> organismsToAdd;
vector <string> logs;
int turn_;
void initializeWorld();
void drawInterface();
void drawInfo();
void drawOrganisms();
void nextTurn();
bool isPositionTaken(int x, int y);
Organism* getOrganism(int x, int y);
void queueOrganismToAdd(Organism* newOrganism);
void addQueuedOrganisms();
void generateStartOrganisms();
bool isPlayerAlive();
public:
void executeMove(Organism* moving, int toX, int toY); //here's the problem
bool isPositionValid(int x, int y);
World(int x, int y);
struct
{
int x_, y_;
} worldSize;
void startGame();
~World();
};
executeMove
void World::executeMove(Organism* moving, int toX, int toY)
{
cout << moving->getSign();
getch();
if (!isPositionTaken(toX, toY)) // <- here it brake
{
moving->setPosition(toX, toY);
}
else if (moving->getSign() == getOrganism(toX, toY)->getSign())
{
//multiply
//make log
}
else {
if (!moving->specialCollision((getOrganism(toX, toY)))) return;
if (!getOrganism(toX, toY)->specialCollision(moving)) return;
if (moving->getPower() >= getOrganism(toX, toY)->getPower())
{
//log
//delete losser
}
else
{
//log
//delete losser
}
moving->setPosition(toX, toY);
}
}
isPositioinTaken
bool World::isPositionTaken(int x, int y)
{
for (int i = 0; i < this->organisms.size(); ++i) // here this is set to 0xcdcdcdcd
{
if (organisms[i]->getPositionX() == x && organisms[i]->getPositionY() == y) return true;
}
return false;
}
Method isPositionTaken is worlking well in other parts of project so im totally lost if finding whats wrong, i aprreciate any help
Since the organisms member has a default constructor, the only way to see this behavior at the line you indicated is if the call to executeMove() was using a pointer which was uninitialized.
Something like:
World *ptr; // not initialized on stack
...
ptr->executeMove();
Or this method was called from another method with the same problem.

C++ Sorting a Array of Pointer to Objects [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
C++ how to sort an array variable
I got a parent class call
Shape
Shape got 2 child call
Square and Rectangle
Shape class got a variable call area, which is of int type
So i created some object of Square, Rectangle like this
int main()
{
Shape *shaped[100];
//then i did some adding of object..
int areaValue;
areaValue=1;
shaped[0] = new Rectangle();
shaped[0]->setArea(areaValue);
areaValue=7;
shaped[1] = new Square();
shaped[1]->setArea(areaValue);
areaValue=5;
shaped[2] = new Square();
shaped[2]->setArea(areaValue);
shapeCounter = 3;
sort(shaped, shaped + 3, sort_by_area());
for (int i=0;i<shapeCounter;i++)
{
cout << shaped[i].getArea() << endl;
}
}
Then at e.g Square.cpp
I did this
struct sort_by_area
{
static bool operator()(Shape* x, Shape* y)
{
return x->getArea() < y->getArea();
}
};
This code above works. and can sort by area, but my question is that can i still sort if i don't use struct , cause if i don't use struct, it will say the sort_by_area is not declared in scope.
Must i really use struct so my main.cpp can access the sort code that is located at the child class .cpp
Thanks
This works perfectly:
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
class Shape{
private:
int x;
public:
void setArea(int x){
this->x = x;
}
int getArea(){
return this->x;
}
};
class Rectangle: public Shape{
public:
};
class Square: public Shape{
public:
};
bool sort_by_area (Shape* x,Shape* y) { return (x->getArea() < y->getArea()); }
int main()
{
Shape *shaped[100];
//then i did some adding of object..
int areaValue,shapeCounter = 0;
areaValue=1;
shaped[0] = new Rectangle();
shaped[0]->setArea(areaValue);
areaValue=7;
shaped[1] = new Square();
shaped[1]->setArea(areaValue);
areaValue=5;
shaped[2] = new Square();
shaped[2]->setArea(areaValue);
shapeCounter = 3;
sort(shaped, shaped + 3, sort_by_area);
for (int i=0;i<shapeCounter;i++)
{
cout << shaped[i]->getArea() << endl;
}
return 0;
}