OOP in C++ newbie [closed] - c++

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!

Related

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

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.

Calculate car movement and distance with C++ classes

This program compiles however, I need to get this function to move on the x & y coordinate and then output the total distance traveled. The xCord moves it right and left while the yCord moves it up and down. I think I need to update my int Taxicab::getDistanceTraveled(), void Taxicab::moveX(int getX), & void Taxicab::moveX(int getX). But for the life of me can't figure out what to do to get it to update properly. When I compile and run it gives me 132617596 for cab1 distance travelled and 0 for the Y coordinate on cab2. Thanks for the help!
#ifndef TAXI_CPP
#define TAXI_CPP
class Taxicab
{
private:
int xCord;
int yCord;
int totalDist;
public:
Taxicab(); //default constructor
Taxicab(int, int); //overload constructor
int getX(); //returns X coordinate
int getY(); //returns Y coordinate
int getDistanceTraveled(); //returns distance calculation
void moveX(int); //moves X left or right
void moveY(int); //moves Y left or right
};
#endif // !TAXI_CPP
#include "Taxi.h"
#include <iostream>
#include <math.h>
#include <cstdlib>
using std::cout;
using std::cin;
using std::endl;
using std::abs;
Taxicab::Taxicab() //default constructor
{
}
Taxicab::Taxicab(int xCord, int yCord) //overload constructor
{
xCord = 0; //initialize to 0
yCord = 0; //initialize to 0
totalDist = 0; //initialize to 0
}
int Taxicab::getX()
{
return xCord; //return x coordinate
}
int Taxicab::getY()
{
return yCord; //return y coordinate
}
void Taxicab::moveX(int getX)
{
int moveX = 0;
moveX = moveX + getX;
}
void Taxicab::moveY(int getY)
{
int moveY = 0;
moveY = moveY + getY;
}
int Taxicab::getDistanceTraveled()
{
return abs(xCord) + abs(yCord);
}
#include <iostream>
#include "Taxi.h"
#include <math.h>
using std::cout;
using std::cin;
using std::endl;
int main()
{
Taxicab cab1;
Taxicab cab2(5, -8);
cab1.moveX(3);
cab1.moveY(-4);
cab1.moveX(-1);
cout << cab1.getDistanceTraveled() << endl;
cab2.moveY(7);
cout << cab2.getY() << endl;
}
Your constructors do not make sense.
In default constructor you have to initialize member variables to something, otherwise their values are undefined and could be set to some random value. Try these maybe:
Taxicab::Taxicab() //default constructor
{
xCord = 0; //initialize to 0
yCord = 0; //initialize to 0
totalDist = 0; //initialize to 0
}
Taxicab::Taxicab(int xCord, int yCord) //overload constructor
{
this->xCord = xCord;
this->yCord = yCord;
totalDist = 0; //initialize to 0
}
Methods to move taxi also do not make much sense. Maybe something like that would be better:
void Taxicab::moveX(int offsetX)
{
totalDist += abs(offsetX);
xCoord += offsetX;
}
void Taxicab::moveY(int offsetY)
{
totalDist += abs(offsetY);
yCoord += offsetY;
}
int Taxicab::getDistanceTraveled()
{
return totalDist;
}

C++ Error: "Multiple markers at this time: no matching function for call to" in constructor

Multiple markers at this line
- candidates are:
- no matching function for call to
'Coordinate::Coordinate()'
I am getting this error in the constructor of my class and I don't understand why. Here is the code involved:
RadialScan header
#ifndef RADIALSCAN_H_
#define RADIALSCAN_H_
#include "EasyBMP/EasyBMP.h"
#include <vector>
#include "Coordinate.h"
using namespace std;
class RadialScan {
vector<int> distanceTimeSeries;
vector<Coordinate> timeSeries;
BMP image;
Coordinate center;
Coordinate getNextPoint(Coordinate c);
bool isBlack(Coordinate c);
void computeTimeSeries();
public:
RadialScan(char* filename);
vector<int> getDistances();
vector<Coordinate> getCoordinates();
};
#endif
RadialScan class (all the methods are implemented, but the error is in the constructor and that's the code I'm providing):
#include "RadialScan.h"
RadialScan::RadialScan(char* filename){
image.ReadFromFile(filename);
int centerX = image.TellWidth()/2;
int centerY = image.TellHeight()/2;
center = Coordinate(centerX, centerY);
}
...
The error seems to be in the constructor. If I remove the constructor everything seems to compile correctly. If I delete the code inside the constructor I'm still getting the error. I don't understand why it keeps asking me for the Coordinate::Coordinate() constructor even when I don't have a coordinate object defined in the RadialScan(char* filename) constructor.
Additionally, these are the files for the Coordinate class:
header:
#ifndef COORDINATE_H_
#define COORDINATE_H_
class Coordinate {
int x;
int y;
public:
Coordinate(int x, int y);
void setX(int oneX);
void setY(int oneY);
int getX();
int getY();
double getMagnitude();
Coordinate operator-(const Coordinate&);
bool operator==(const Coordinate&);
Coordinate operator=(const Coordinate&);
};
#endif
cpp class:
#include "Coordinate.h"
#include <math.h>
Coordinate::Coordinate(int oneX, int oneY) {
x = oneX;
y = oneY;
}
//Setters
void Coordinate::setX(int oneX) {
x = oneX;
}
void Coordinate::setY(int oneY) {
y = oneY;
}
//Getters
int Coordinate::getX() {
return x;
}
int Coordinate::getY() {
return y;
}
double Coordinate::getMagnitude() {
return sqrt(x * x + y * y);
}
Coordinate Coordinate::operator-(const Coordinate& p) {
return Coordinate(x - p.x, y - p.y);
}
bool Coordinate::operator==(const Coordinate& p) {
return x == p.x && y == p.y;
}
Coordinate Coordinate::operator=(const Coordinate& p) {
return Coordinate(p.x, p.y);
}
Your constructor must look like
RadialScan::RadialScan(char* filename) : center (0, 0) {
image.ReadFromFile(filename);
int centerX = image.TellWidth()/2;
int centerY = image.TellHeight()/2;
center = Coordinate(centerX, centerY);
}
this because you did not implement default constructor and you can not create center object by default, so the only way is to call explicity Coordinate constructor with some default values.

Sweep Line algorithm [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
SWEEP LINE EXAMPLE WITH EXAMPLE: AFTER CORRECTION
The code Contais 3 classes:
Class Line to represent the Horizontal lines: Parameters:
(x1,y1)----------(x2,y2)
Class Point:
Class segment for the sweep line algorithm
I am trying to use the following code, to compute the intersections between horizontal lines, As you can from the coordinates that My lines are Horizontal:
Coordinates: x1,y1,x2,y2 I have x1 < x2, and y1 = y
Class Point:
#ifndef POINT_H
#define POINT_H
class Point
{
public:
Point(float, float);
float x;
float y;
};
#endif // POINT_H
#include "Point.h"
Point::Point(float xi, float yi):x(xi),y(yi)
{
}
Class Line
#ifndef LINE_H
#define LINE_H
class Line
{
public:
Line(int,int,int,int);
int x1, y1, x2, y2;
};
#endif // LINE_H
#include "Line.h"
Line::Line(int x_1, int y_1, int x_2,int y_2):x1(x_1),y1(y_1),x2(x_2),y2(y_2)
{
//ctor
}
Class Segment:
#ifndef SEGMENT_H
#define SEGMENT_H
#include "Point.h"
#include "Line.h"
#include <vector>
#include <set>
#include <algorithm>
using namespace std;
enum event_type { EVENT_END,EVENT_VERTICAL,EVENT_START};
struct event
{
event_type type;
int x;
int line; // index into list of lines
event() {}
event(event_type type, int x, int line) : type(type), x(x), line(line) {}
// sort by X then by type
bool operator <(const event &b) const
{
if (x != b.x) return x < b.x;
else return type < b.type;
}
};
class Segment
{
public:
Segment();
vector<Point> hv_intersections(const vector<Line> &);
};
#endif // SEGMENT_H
#include "Segment.h"
Segment::Segment()
{
//ctor
}
vector<Point> Segment::hv_intersections(const vector<Line> & lines)
{
int L = lines.size();
vector<event> events;
vector<Point> ans;
// Y coordinates of active lines
multiset<int> active;
// Convert lines into events
for (int i = 0; i < L; i++)
{
if (lines[i].y1 != lines[i].y2)
events.push_back(event(EVENT_VERTICAL, lines[i].x1, i));
else if (lines[i].x1 != lines[i].x2)
{
events.push_back(event(EVENT_START, lines[i].x1, i));
events.push_back(event(EVENT_END, lines[i].x2, i));
}
}
// Sort events by X
sort(events.begin(), events.end());
// Returns all intersections between lines. The lines must all be either
// horizontal and vertical, and only horizontal-vertical intersections are
// counted (i.e. not overlaps). Lines are considered to exclude their
// endpoints. Also, each line must have x1 <= x2 and y1 <= y2.
for (vector<event>::const_iterator e = events.begin(); e != events.end(); ++e)
{
switch (e->type)
{
case EVENT_START:
active.insert(lines[e->line].y1);
break;
case EVENT_END:
active.erase(active.find(lines[e->line].y1));
break;
case EVENT_VERTICAL:
{
// Iterate over all y values for intersecting horizontal lines
multiset<int>::const_iterator first, last, i;
first = active.upper_bound(lines[e->line].y1);
last = active.lower_bound(lines[e->line].y2);
for (i = first; i != last; ++i)
ans.push_back(Point(e->x, *i));
}
break;
}
}
return ans;
}
int main()
{
vector<Line> v;
v.push_back(Line(0, 5, 10, 5));
v.push_back(Line(5, 0, 5, 10));
Segment s;
vector<Point> p = s.hv_intersections(v);
cout << p.size() << endl;
return 0;
}
The code is correct (assuming you have proper #include and main() methods). The lines you provided have no intersections. If you add any vertical line like 800 100 800 2000 you will get a vector<pnt> of intersections.
Parallel lines (in this case horizontal lines) do not intersect. Never.
http://en.wikipedia.org/wiki/Parallel_(geometry)

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;
}