Class of dynamic array - c++

I've been working on a C++ exercise and I was unable to figure out how to do it correctly, let me explain it:
I made this class based on the 1st question of the exercise
class cylinder
{
private:
float height;
float radius;
char * label;
public:
cylinder(float, float, char *);
cylinder();
cylinder(const cylinder &);
~cylinder();
};
The 2nd question was:
Create a new class "form3D" contain cylinders (dynamic array of cylinder)
How to make a default constructor & constructor with parameters?
This is what I did:
class forme3d
{
cylinder * tab;
int tabsize;
public:
forme3d();
forme3d(cylinder * , int);
~forme3d();
};
forme3d::forme3d(cylindre * c, int t)
{
cylindre * tab = new cylindre[t];
for (int i = 0; i < t; ++i)
{
tab[i] = c[i];
}
}
This cause an error about "operator=" not defined for this line "tab[i] = c[i];"

Related

How to make a loop that instanciates classes and sort them in a address list?

Consider 2 variables (number of polygons and its coordinates) :
int numberPoly= 2;
float polycoord[18]= {0,50,0,0,0,0,50,0,0,0,50,0,50,50,0,50,0,0};
, a Model class (that is intended to store polygon classes to a list) :
class model{
public:
model();
void affect(int id, int address){
polyclasses[id]=address;
}
private:
string name;
vector<int> polyclasses;
};
, a Polygon class (that I have to sort in Model's polyclasses list) :
class polygone {
public:
polygone();
void affect(int id, int coord){
ABC[id]=coord;
}
private:
int id;
float ABC[9]={0.0};
};
I wanted to code a function (cf. "builder") that instanciate n Polygon classes and sort them (with their memory addresses like an id) in an array ("polyclasses" from Model class). So, I don't arrive. Here is a bit of my builder function not acomplished :
void builder(){
int from = 0; int subfrom = 0;
for(int i=0; i < numberPoly - 1; i++){
from = 0; subfrom = 0;
polygone poly();
!!! need to put that instance in Model's polygon list !!!
...
for(int j=from; j < (polycoord.size())-1; j++){
poly.affect(subfrom, polycoord[j]) ...
subfrom++;
}
from += 3;
}
}
This is for my first c++ project. I'm coding a light 2d engine.
You need to store pointer of instances in your vector and allocate your objects with new keyword. At destructor of your model yo uwill need to deletethe object to avoid a memory leak.
// Model.h
// Class name should begin with uppercase by convention
class Model{
public:
Model();
~Model();
void builder();
// Implementation should go in cpp file
void affect(int id, int address);
private:
// Having a m_ prefix on private variable is useful to make your code more readable so a reader can easily know if a variable is private or not
string m_name;
vector<Polygon*> m_polyclasses;
};
// Polygone.h
class Polygone {
public:
Polygone();
// Don't forget destructor
~Polygone();
// Implementation should go in cpp file
void affect(int id, int address);
private:
int m_id;
// Use std::array in C++ and give meaningful name to your variable
// float m_ABC[9]={0.0}; is replaced by :
std::array<float, 9> m_coordinates;
};
// Model.cpp
void Model::builder() {
int from = 0; int subfrom = 0;
for(int i=0; i < numberPoly - 1; i++){
from = 0; subfrom = 0;
Polygone * poly = new Polygone();
// A pointer of poly is now stored in Model
this->polyclasses.push_back(poly);
// Your polygone object should initialized in the constructor or in a member function of the class Polygone.
for(int j=from; j < (polycoord.size())-1; j++){
poly->affect(subfrom, polycoord[j]) ...
subfrom++;
}
from += 3;
}
}
Model::~Model() {
for(auto p: this->polyclasses) {
// Avoid memory leak
delete p;
}
this->polyclasses.clear();
}
You can also store a std::unique_ptr instead of a plain pointer. In that case you don't need to delete.

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.

Sorting vector of objects with operator overloading in c++

I have one base class and I have 4 class derived.of course I write 2 class for example.
I created vector and fill it by objects of derived classes, then I want sort my vector base of area function. I want use operator overloading.
I define operator overloading but it not Completely!
please help me!
Thanks....
class Shape
{
public:
Shape() {}
virtual void draw() = 0;
virtual int area() = 0;
virtual void perimeter() = 0;
bool operator >(Shape * shape_one , Shape* shape_two )
{
return shape_one->area() > shape_two->area();
}
protected :
double height;
double width;
};
class Squar : public Shape
{
public:
Squar(int _width) {
width = _width;
}
void draw(){}
int area(){
return width * width;
}
void perimeter(){}
bool operator >(Squar * squar_one , Squar* squar_two )
{
return squar_one->area() > squar_two->area();
}
};
class Triangle : public Shape
{
public:
Triangle(int _width , int _height) {
width = _width;
height = _height;
}
void draw(){}
int area(){
return (width * height) / 2;
}
void perimeter(){}
bool operator >(Triangle * triangle_one , Triangle* triangle_two )
{
return triangle_one->area() > triangle_two->area();
}
};
int main()
{
Shape *rect = new Rectangular( 1 , 9);
Shape *squar = new Squar(5);
QVector <Shape *> list;
list.push_back(rect);
list.push_back(squar);
retuurn 0;
}
I understand answer the question.
add following code in base class :
bool operator <( Shape *item )
{
return this->area() < item->area();
}
and add following code in main :
std ::sort(list.begin() , list.end() ,[](Shape* ptr_l , Shape* ptr_r) { return *ptr_l < ptr_r;} );
This code is correct! :)

I can't display variables of different types included in array

I have to do a program for college.
I have 3 classes already declared in the statement of the problem.
First class:
class piesa_a{
protected:
int id;
char *tip;
int pret;
};
Second class:
class piesa_b:public piesa_a
{
private:
float lungime;
bool bw;
};
Third class:
class piesa_c:public piesa_a
{
private:
int nr;
piesa_b *buf;
};
In main I need to create an array in which to store items such piesa_a, piesa_b, piesa_c. Then I have to sort items by price.
I have this code so far: http://pastebin.com/nx2FGSfe
The program is incomplete because it does not displays each item in the array.
I got stuck here. But if you display the array's elements when they are outside of it, it works.
SHORT: I have an error on line 143 and I want to solve it.
main.cpp:143:18: error: request for member ‘afisare’ in ‘*(v + ((unsigned int)(((unsigned int)i) * 4u)))’, which is of non-class type ‘piesa_a*’
The code is here:
#include <cstdlib>
#include<iostream>
#include<string.h>
using namespace std;
class piesa_a{
protected:
int id;
char *tip;
int pret;
public:
piesa_a()
{
id = 0;
tip = new char[1];
pret = 0;
}
piesa_a(int aidi, char *typ, int pretz)
{
id = aidi;
tip = new char[strlen(typ)+1];
strcpy(tip,typ);
pret = pretz;
}
piesa_a&operator =(piesa_a alta)
{
id = alta.id;
tip = new char[strlen(alta.tip)+1];
strcpy(tip,alta.tip);
pret = alta.pret;
return *this;
}
virtual void afisare()
{
cout<<"\n Piesa A: "<<id<<" "<<tip<<" "<<pret;
}
};
class piesa_b:public piesa_a
{
private:
float lungime;
bool bw;
public:
piesa_b():piesa_a(){lungime = 0;bw = 0;}
piesa_b(float lg,bool bl, int aid, char *tipi, int pretzz):piesa_a(aid,tipi,pretzz)
{
lungime = lg;
bw = bl;
}
piesa_b&operator =(piesa_b &c)
{
id = c.id;
tip = new char[strlen(c.tip)+1];
strcpy(tip,c.tip);
pret = c.pret;
lungime = c.lungime;
bw = c.bw;
return *this;
}
void afisare()
{
piesa_a::afisare();
cout<<"impreuna cu piesa B: "<<lungime<<" "<<bw<<"\n";
}
};
class piesa_c:public piesa_a
{
private:
int nr;
piesa_b *buf;
public:
piesa_c():piesa_a(){nr=0; buf = new piesa_b[nr];}
piesa_c(int n, piesa_b *bu,int aid, char *tipi, int pretzz):piesa_a(aid,tipi,pretzz)
{
nr = n;
buf = new piesa_b[nr];
for(int i=0;i<nr;i++)
buf[i]= bu[i];
}
piesa_c&operator =(piesa_c &alta)
{
id = alta.id;
tip = new char[strlen(alta.tip)+1];
strcpy(tip,alta.tip);
pret = alta.pret;
nr = alta.nr;
for(int i=0;i<alta.nr;i++)
buf[i] = alta.buf[i];
}
void afisare()
{
for(int i=0;i<nr;i++)
buf[i].afisare();
}
};
int main(int argc, char** argv) {
piesa_b *H;
H = new piesa_b[2];
piesa_a A(4,"TIPA",120);
piesa_b B(100,1,3,"TIPA",120);
H[0]=B;
H[1]=B;
piesa_c C(2, H,14,"TIPC",20);
piesa_a** v = new piesa_a*[3];
v[0] = &A;
v[1] = &B;
v[2] = &C;
for(int i=0;i<3;i++)
v[i].afisare();
return 0;
}
What's wrong?
In C++ (and current C), casts are almost always a sign that the programmer didn't know how to use the language as it is supposed to be used. If you need an array of 3 types of data, the cleanest solution is an array of objects of a class that is base to the 3. And if you want to display each item differently, you'll want to overload the << operator, so you just iterate over the array and go << on each item. Sorted by price means that the class includes a price field, and you use the sort from the standard template library, passing a comparison operation that just compares prices.

Weird error in Turbo C++ IDE - Class template related question

Basically I'm trying to compile a template class which is meant to represent a table for adding up polynomials. As a result of this the table needs to be nullable.
This is the sort of thing I am trying to represent http://www.mathsisfun.com/algebra/polynomials-adding-subtracting.html.
And this is the template which is meant to do it:
template <class T> class TableWithBlanks : public Table<T> {
public:
TableWithBlanks( const int width, const int height ) : w(width), h(height), table_contents( new t_node[width][height]
{
table_contents = new t_node[width][height];
// Go through all the values and blank them.
for( int i = 0; i < w; i++)
{
for( int a = 0; a < h; a++)
{
table_contents[i][a].value_ptr = NULL;
}
}
}
void set_value( const int width, const int height, const T* table_value_ptr)
{
if( width <= w && height <= h )
{
table_contents[w][h] = table_value_ptr;
}
}
T* get_value( const int width, const int height)
{
if( width <= w && height <= h )
{
return table_contents[width][height];
}
}
private:
typedef struct node {
T* value_ptr;
} t_node;
t_node** table_contents;
int w;
int h;
};
And this is the error I am getting:
[C++ Error] TableWithBlanks.h(16):
E2034 Cannot convert
'TableWithBlanks::node
( *)[1]' to
'TableWithBlanks::node
* *'
The PolynomialNode class is a class which is a linked list, where each node in the list represent the terms in a simple polynomial - I don't need to go into details.
In this line, you're trying to dynamically construct a two-dimensional array:
table_contents = new t_node[width][height];
but C++ doesn't work this way. For an example of how to allocate two-dimensional arrays, see this question, for example.