declaring an array using new in a class c++ - c++

#include <iostream>
using namespace std;
class Point {
int x, y;
public:
Point ():x(0),y(0){};
void setX (int xx){x = xx;};
void setY (int yy){y = yy;};
int getX (){return x;};
int getY (){return y;};
};
class Polygon {
int n;
double degree;
Point* vertex;
public:
Polygon (int nn):n(nn){
degree = 360.0 / n;
//vertex = new Point [n];
};
private:
vertex = new Point [n];
};
so I'm trying to declare vertex array using new, but I keep getting this error: data member initializer is not allowed
is 'new' considered initializing?! and I tried doing it in constructor but I think it'll only work in constructor's scope.
I'm also confused about this: n should be initialized before using new, so will this be solved if I just write the declaration after constructor?

class Point {
public:
Point ():x(0),y(0){};
void setX (int xx){x = xx;}
void setY (int yy){y = yy;}
int getX (){return x;}
int getY (){return y;}
//change access level to 'private'.
private:
int x;
int y;
};
class Polygon {
public:
Polygon (int nn):n(nn){
degree = 360.0 / n;
vertex = new Point [n];
}
// deallocate memory from heap
~Polygon () {
delete [] vertex;
}
// overload copy constructor to avoid double free
Polygon (const Polygon& pg) : n(pg.n), degree(pg.degree) {
vertex = new Point [n];
for (int i = 0; i < n; i++) {
vertex[i] = pg.vertex[i];
}
}
// overload assignment operator to avoid memory leak
Polygon& operator=(const Polygon& pg) {
if (this != &pg) {
n = pg.n;
degree = pg.degree;
delete [] vertex;
vertex = new Point[n];
for (int i = 0; i < n; i++) {
vertex[i] = pg.vertex[i];
}
}
return *this;
}
// use pointer to change/get the value.
Point* get_vertex() {
return vertex;
}
//change access level to 'private'.
private:
int n;
double degree;
Point* vertex;
};

Related

Array of arrays of different types of shapes

I want to create a "3D console game" using RayCasting. To begin with, I needed a container with all the information about the world. First of all, I started with just two shapes, a rectangle and a circle. Actually, here's how I implemented them:
enum POINTS
{
POINT_1,
POINT_2
};
enum ASIXS
{
ASIX_X,
ASIX_Y,
};
class Point
{
private:
double properties[2];
public:
Point()
{
properties[ASIX_X] = 0;
properties[ASIX_Y] = 0;
}
Point(double x, double y)
{
properties[ASIX_X] = x;
properties[ASIX_Y] = y;
}
double& operator[] (int index)
{
return properties[index];
}
};
class Rectangle
{
private:
Point base[2];
public:
//Points getter
Point& operator[](int index)
{
return base[index];
}
};
class Circle
{
private:
Point center;
double radius = 0;
public:
Point& getCenter()
{
return center;
}
double& getRadius()
{
return radius;
}
};
Next, I need a generic container. Obviously this should be a pattern:
template<typename T>
class ObjectArr
{
protected:
int qty;
T* objs;
public:
ObjectArr()
{
qty = 0;
objs = nullptr;
}
~ObjectArr()
{
delete[] objs;
}
void add()
{
T* temp = new T[++qty];
for (int i = 0; i < qty - 1; i++)
temp[i] = objs[i];
delete[] objs;
objs = temp;
}
T getObj(int index)
{
return objs[index];
}
};
Here's what it will look like:
#include <iostream>
using namespace std;
int main()
{
ObjectArr<Rectangle> rect;
rect.add();
//rect.getObj(id)[point][asix]
rect.getObj(0)[POINT_1][ASIX_X] = 5;
cout << rect.getObj(0)[POINT_1][ASIX_X]; //Out 5
ObjectArr<Circle> cir;
cir.add();
//cir.getObj(id).getCenter()[asix]//getRadius()
cir.getObj(0).getCenter() = {0, 0};
return 0;
}
And in the end, I would like one common container that would store ObjectArr<>. From the beginning I thought about polymorphism. Something like this:
#include <vector>
class Container
{
//...
};
template<typename T>
class ObjectArr : public Container
{
//...
};
int main()
{
vector<Container*> test;
test.push_back(new ObjectArr<Rectangle>);
test.push_back(new ObjectArr<Circle>);
test[0]->add();
//...
return 0;
}
But with this approach, the function T getObj(int index) cannot be used from such a container. And writing it as a virtual one will not work either because of the template. And I also don’t want to prescribe every possible shape, so that it would be easier to add new shapes. Wrote a class of a new figure and all. Tell me, please, how should I be and what should I do, maybe I need to completely change the approach?

how do i initialize a public variable in a public class method

I have a public class in which I create an array, this array takes its size from the constructor and needs to be used in other functions (including int main). Therefore the variable must be public. my code looks something along these lines:
class myclass {
public:
int parameter1;
int parameter2;
myclass(int p, int p2) {
parameter1 = p;
parameter2 = p2;
}
void makeArray() {
int array[parameter1][parameter2]; //I want this array to be public as the next method needs access to it
}
void otherFunction() {
array[1][2] = 5; //just an example of what i need to do
}
}
Look up how to use pointers and dynamic memory..
To do what you want would be something like:
class myclass {
public:
int parameter1;
int parameter2;
int **a;
myclass(int p, int p2) {
parameter1 = p;
parameter2 = p2;
a = nullptr;
}
~myclass() {
// TODO: delete "a"
}
void makeArray() {
// TODO: delete "a" if it has already been allocated
a = new *int[parameter1];
for (int i = 0; i < parameter1; ++i) {
a[i] = new int[parameter2];
}
}
void otherFunction() {
// TODO: check that "a" has already been allocated
a[1][2] = 5; //just an example of what i need to do
}
}
You could also allocate the array in the constructor since you have the necessary information being passed in already.
This is more optimized way to do the same thing:
class myclass {
public:
int parameter1;
int parameter2;
int *array;
myclass(int p1, int p2) {
parameter1 = p1;
parameter2 = p2;
}
void makeArray() {
array = new int[parameter1*parameter2];
}
void otherFunction() {
// ary[i][j] is then rewritten as ary[i*sizeY+j]
array[1*parameter2+2] = 5;
}
};
int main()
{
int sizeX = 5;
int sizeY = 5;
myclass m1(sizeX,sizeY);
m1.makeArray();
m1.otherFunction();
cout << m1.array[1*sizeY+2] << endl;
return 0;
}

How to construct base class multiple times in derived constructor

Hello I I have problem on my assignment which I need to init base constructor which is point multiple time in derived constructor which is polygon.
The polygon have at least 3 point , each point have a coordinate value. any one have ideas how to init base constructor multiple time in constructor init?
The inheritance ideas is not my ideas , is the assignment question.
this is the question
Polygon  (constructor) creates a polygon with npoints vertices, the vertices take their values from those stored in the array points. Note that the array points should not be assumed to persist; it may be deleted after the constructor is invoked.
struct PointType
{
float x;
float y;
};
class Point
{
public:
Point(const PointType& center );
virtual ~Point();
private:
PointType m_center;
};
class Polygon : public Point
{
public:
Polygon(const PointType* points, int npoints);
~Polygon();
const VectorType& operator[](int index) const;
private:
int m_npoints;
Object::PointType * m_pt;
};
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <cmath>
#include "Object.hpp"
using namespace std;
const float eps = 1e-5f;
bool Near(float x, float y)
{
return abs(x-y) < eps;
}
float frand()
{
return 10.0f*float(rand())/float(RAND_MAX);
}
int main()
{
srand(unsigned(time(0)));
int count = 0,
max_count = 0;
// Polygon tests
int n = 3 + rand()%8;
float *xs = new float[n],
*ys = new float[n];
float x = 0, y = 0;
PointType *Ps = new PointType[n];
for (int i=0; i < n; ++i) {
xs[i] = frand(), ys[i] = frand();
Ps[i] = PointType(xs[i],ys[i]);
x += xs[i], y += ys[i];
}
}
Point::Point(const PointType& center)
: m_center{center}
{
}
// this is wrong, can correct me how to construct it?
Polygon::Polygon(const PointType* points, int npoints, float depth)
:m_npoints{npoints} , m_pt{new Object::PointType[npoints]}, Point (*m_pt ,depth)
{
for(int i=0; i < m_npoints ; ++i)
{
m_pt[i] = points[i];
}
}
enter code here
this the assignment structure like
enter image description here
I took away other object class implementation
Your assignment text doesn't say anything about inheritance. It essentially describes composition. Go from here:
class Polygon
{
public:
// constructor should allocate the array
Polygon(const PointType* points, int npoints);
~Polygon();
private:
Point *m_npoints; // or use smart pointer if you're allowed to.
};
It is a trick question, is actually want me to find centroid point of polygon.
So I need a private compute center point of polygon function and return the result of center point of polygon, and then call the function in point constructor when init.

Passing an integer pointer to a constructor and getting runtime memory error

I'm trying to create a vector of a class-name vertex. The value of "n" is not known at compile-time so I'll be using new to create to create the "path" array. But the problem occurs when I create the input array in a function and push it in the vector.
int n;
class vertex {
public:
int *path;
int visited = 0;
vertex(int *y) {
path = new int(n);
for (int i = 0; i < n; i++)
path[i] = y[i];
}
};
void inp(vector<vertex> graph) {
int t1[] = { 0,1,0,0 };
int t2[] = { 0,0,1,0 };
int t3[] = { 0,0,0,1 };
int t4[] = { 0,0,0,0 };
graph.push_back(vertex(t1));
graph.push_back(vertex(t2));
graph.push_back(vertex(t3));
graph.push_back(vertex(t4));
}
int main() {
n=4;
vector<vertex> graph;
inp(graph);
_getch();
}
For simplicity I've created t1 to t4 as static arrays. But still it shows some error at runtime
1:try use: path = new int [n], rather than path = new int(n);
2:if you want to push elements to graph, you should change your function inp to void inp(vector<vertex>& graph)

Creating 2D-Array inside a constuctor in C++

I am trying to do the following:
class Test{
private:
int x;
int y;
// Create array[][] here
public:
Test(const int x, const int y){
this->x = x;
this->y = y;
// set: array[x][y] here
}
};
As you see I would like to create a 2d-Array, while the bounds will be given in the constructor.
How can I achieve this?
It works with an usual array:
class Test{
private:
int x;
int y;
int *array;
public:
Test(const int x, const int y){
this->array = new int[x]; // works
// this->array = new int[x][y] does not work
this->x = x;
this->y = y;
}
};
You may be bumping into the problem of "All dimensions must be constants except the leftmost" discussed here.
Instead, try the following:
class Test {
private:
int x;
int y;
int** myArray;
public:
Test(const int x, const int y) : x(x), y(y) {
myArray = new int*[x];
for (int firstDimension = 0; firstDimension < x; firstDimension++) {
myArray[firstDimension] = new int[y];
for (int secondDimension = 0; secondDimension < y; secondDimension++) {
myArray[firstDimension][secondDimension] = secondDimension;
}
}
}
~Test() {
for(int i = 0; i < x; i++)
delete[] myArray[i];
delete[] myArray;
}
};
you should consider allocating memory with pointers, should be as follows:
class Test{
private:
int x;
int y;
int **array;
public:
Test(const int x, const int y){
int i;
this->array = new int*[x]; // first level pointer asignation
for(i=0;i<x;i++){
this->array[x] = new int[y]; // second level pointer asignation
}
// this->array = new int[x][y] does not work
this->x = x;
this->y = y;
}
};
see this.