Class constructor does not take input parameters C++ (all attributes get the same value and the same value applies to all objects) - c++

I created a class named Triangle that takes triangles as objects.
The attributes are the ID of the triangle (m_ID), the index of the three vertices (m_S1, m_S2, m_S3) and the index of the three adjacent triangles (m_T1, m_T2, m_T3).
I want to create a triangle object by passing input parameters in the constructor.
The parameters are passed by value, but the object is badly created. In fact, all three triangles I tried to create (triangle2, 3 and 4) have the same value for attributes. The value is -858993460 which looks like an address.
Even when I use the simplest input values (Triangle triangle4(1,1,1,1,1,1,1)), the attributes are not created correctly.
/*
Name: insert
Description: insert the new point and create 3 new triangles
*/
void insert(const int triangleIndex)
{
// Extract the Index of the new point
int newPointIndex = pointList.size();
// Create the line of the second new triangle
Triangle triangle2(triangleList.size() + 1, newPointIndex, triangleList[triangleIndex].getS3(), triangleList[triangleIndex].getS1(), triangleList[triangleIndex].getT2(), triangleList.size() + 2, triangleIndex);
// Create the line of the third new triangle
Triangle triangle3(triangleList.size() + 2, newPointIndex, triangleList[triangleIndex].getS1(), triangleList[triangleIndex].getS2(), triangleList[triangleIndex].getT3(), triangleIndex, triangleList.size() + 1);
// Test only
Triangle triangle4(1, 1, 1, 1, 1, 1, 1);
// Get the adjacent triangles of the base triangle
int T1 = triangleList[triangleIndex].getT1();
int T2 = triangleList[triangleIndex].getT2();
int T3 = triangleList[triangleIndex].getT3();
// Update the line of first new triangle
triangleList[triangleIndex].setS1(newPointIndex);
triangleList[triangleIndex].setT2(triangleList.size() + 1);
triangleList[triangleIndex].setT3(triangleList.size() + 2);
// Update the adjacent triangles
triangleList[T2].setT3(triangleList.size() + 1);
triangleList[T3].setT2(triangleList.size() + 2);
// Insert the new triangles in the triangulation
triangleList.push_back(triangle2);
triangleList.push_back(triangle3);
}
/*-----------------------------------------
Name: Triangle
Author: Michael Landry
Description: Implementation of class Triangle
Date: 2018-02-23
Version: 1.00
-------------------------------------------*/
#include "Triangle.h"
// Constructor with no parameter
Triangle::Triangle() : m_ID(0), m_S1(0), m_S2(0), m_S3(0), m_T1(0), m_T2(0), m_T3(0)
{
}
// Constructor with parameters
Triangle::Triangle(int p_ID, int p_S1, int p_S2, int p_S3, int p_T1, int p_T2, int p_T3) : m_ID(p_ID), m_S1(p_S1), m_S2(p_S2), m_S3(p_S3), m_T1(p_T1), m_T2(p_T2), m_T3(p_T3)
{
}
// Global setter
void Triangle::setTriangle(int p_ID, int p_S1, int p_S2, int p_S3, int p_T1, int p_T2, int p_T3)
{
m_ID = p_ID;
m_S1 = p_S1;
m_S2 = p_S2;
m_S3 = p_S3;
m_T1 = p_T1;
m_T2 = p_T2;
m_T3 = p_T3;
}
// Setter for each individual parameter
void Triangle::setID(int p_ID)
{
m_ID = p_ID;
}
void Triangle::setS1(int p_S1)
{
m_S1 = p_S1;
}
void Triangle::setS2(int p_S2)
{
m_S2 = p_S2;
}
void Triangle::setS3(int p_S3)
{
m_S3 = p_S3;
}
void Triangle::setT1(int p_T1)
{
m_T1 = p_T1;
}
void Triangle::setT2(int p_T2)
{
m_T2 = p_T2;
}
void Triangle::setT3(int p_T3)
{
m_T3 = p_T3;
}
// Getter for each individual parameter
int Triangle::getID() const
{
return m_ID;
}
int Triangle::getS1() const
{
return m_S1;
}
int Triangle::getS2() const
{
return m_S2;
}
int Triangle::getS3() const
{
return m_S3;
}
int Triangle::getT1() const
{
return m_T1;
}
int Triangle::getT2() const
{
return m_T2;
}
int Triangle::getT3() const
{
return m_T3;
}
/*-----------------------------------------
Name: Triangle
Author: Michael Landry
Description: Declaration of class Triangle
Date: 2018-02-23
Version: 1.00
-------------------------------------------*/
#ifndef TRIANGLE_H_
#define TRIANGLE_H_
class Triangle
{
public:
// Constructor with no parameter
Triangle::Triangle();
// Constructor with parameters
Triangle::Triangle(int, int, int, int, int, int, int);
// Setters
void Triangle::setTriangle(int p_ID, int p_S1, int p_S2, int p_S3, int p_T1, int p_T2, int p_T3);
void Triangle::setID(int p_ID);
void Triangle::setS1(int p_S1);
void Triangle::setS2(int p_S2);
void Triangle::setS3(int p_S3);
void Triangle::setT1(int p_T1);
void Triangle::setT2(int p_T1);
void Triangle::setT3(int p_T1);
// Getters
int Triangle::getID() const;
int Triangle::getS1() const;
int Triangle::getS2() const;
int Triangle::getS3() const;
int Triangle::getT1() const;
int Triangle::getT2() const;
int Triangle::getT3() const;
private:
// The ID of the triangle
int m_ID;
// The 3 vertices forming the triangle
int m_S1;
int m_S2;
int m_S3;
// The 3 adjacent triangles
int m_T1;
int m_T2;
int m_T3;
};
#endif /* TRIANGLE_H_ */

Related

How do I define and set a a pointer to a 2d array that's passed twice in the middle class

I have an array in my MainProcessor
float waveforms[2][1080] = { {0}, {0} };
And I pass it to a SynthVoice like this:
osc1Voice->setWavetable(waveforms, 0); //[1]
osc2Voice->setWavetable(waveforms, 1);
There I read it like this in SynthVoice.h:
typedef float array_of_wavetable[1080];
void setWavetable(array_of_wavetable* waveform, int number)
{
wavetable = waveform;
id = number;
}
so i can use it like this in my SynthVoice class:
wavetable[id][first_sample + int(phase_0)]
Now I have moved [1] in a new class (OscilatorProcessor.h) and I want to set a pointer from MainProcessor -> OscillatorProcessor -> SynthVoice in a way that I can use it as wavetable[id][phase].
Now I don't know how to pass it from my MainProcessor to my OscillatorProcessor in the middle. So I can read it in the same way in the SynthVoice class.
I hope this made sense. Thank you for your time
edit: minimal reproducible example
#include <iostream>
typedef float array_of_wavetable[1080];
class SynthVoice
{
public:
void setWavetable(array_of_wavetable* waveform, int number)
{
wavetable = waveform;
id = number;
}
void outputWavetable()
{
for(int i = 0; i < 1080; i++)
{
std::cout << wavetable[id][i];
}
}
private:
array_of_wavetable * wavetable;
int id;
};
class OscillatorProcessor
{
public:
void setWavetable(array_of_wavetable * waveform, int number)
{
wavetable = waveform;
id = number;
}
void sendWaveToVoice()
{
SynthVoice voice;
voice.setWavetable(wavetable, id);
voice.outputWavetable();
}
private:
array_of_wavetable * wavetable;
int id;
};
int main() {
float waveform_templates[4][1080] = { {0}, {0}, {0}, {0} };
OscillatorProcessor oscillator;
oscillator.setWavetable(waveform_templates, 2);
return 0;
}

Too many initializers while printing char 2D array

#include<iostream>
using namespace std;
// bool turnright(char **arr,int &x,int &y,bool &quit)
// {}
// bool turnright(char **arr,int &x,int &y,bool &quit)
// {}
// bool moveforward(char **arr,int &x,int &y,bool &quit)
// {}
// bool movebackward(char **arr,int &x,int &y,bool &quit)
// {
// }
void print(char arr[][12])
{
for (int i=0;i<12;i++)
{
for (int j=0;j<12;j++)
{
cout<<arr[i][j];
}
cout<<endl;
}
}
int main()
{
char arr[12][12]={
{'#','#','#','#','#','#','#','#','#','#','#','#'},
{'#','.','.','.','#','.','.','.','.','.','.','#'},
{'#','.','#','.','#','.','#','#','#','#','.','#'},
{'#','#','#','.','#','.','.','.','.','#','.','#'},
{'#','.','.','.','.','#','#','#','.','#','.','.'},
{'#','.','.','.','.','#','#','#','.','#','.','.'},
{'#','.','.','#','.','#','.','#','.','#','.','#'},
{'#','#','.','#','.','#','.','#','.','#','.','#'},
{'#','.','.','.','.','.','.','.','.','#','.','#'},
{'#','#','#','#','#','#','.','#','#','#','.','#'},
{'.','.','.','.','.','.','.','.','#','.','.','.','#'},
{'#','#','#','#','#','#','#','#','#','#','#','#'}
};
// bool quit=false;
// int Ix;
// int IY;
// while(!quit)
// {
// moveforward();
// turnfight();
// if (!moveforward())
// {
// turnleft();
// if (!turnleft)
// {
// moveback();
// turnleft();
// if(!turnleft())
// {
// turnright();
// }
// }
// }
// }
print(arr);
}
I am trying to write code for traversing a maze while printing maze I am getting an error too many initiallizers although i have given number of rows and columns properly could any one please tell me where i am wrong ...
I reformatted your array initialization and see that row 11 has 13 elements which won't fit in an [12][12] array:
char arr[12][12]={
{'#','#','#','#','#','#','#','#','#','#','#','#'},
{'#','.','.','.','#','.','.','.','.','.','.','#'},
{'#','.','#','.','#','.','#','#','#','#','.','#'},
{'#','#','#','.','#','.','.','.','.','#','.','#'},
{'#','.','.','.','.','#','#','#','.','#','.','.'},
{'#','.','.','.','.','#','#','#','.','#','.','.'},
{'#','.','.','#','.','#','.','#','.','#','.','#'},
{'#','#','.','#','.','#','.','#','.','#','.','#'},
{'#','.','.','.','.','.','.','.','.','#','.','#'},
{'#','#','#','#','#','#','.','#','#','#','.','#'},
{'.','.','.','.','.','.','.','.','#','.','.','.','#'},
{'#','#','#','#','#','#','#','#','#','#','#','#'}
};

Problems with using classes as other classes's member data in C++

I was using this code: The first is Rectangle.hpp
#include <iostream>
//Point
class point {
public:
void setxy(int nx, int ny);
const int getx();
const int gety();
private:
int x;
int y;
};
void point::setxy(int nx, int ny) {
x = nx;
y = ny;
};
const int point::getx() { return x; };
const int point::gety() { return y; };
//Rectangle
class rectangle {
public:
rectangle(point nLl, point nLr, point nUl, point nUr);
void getArea();
const point getLl() { return Lleft; };
const point getLr() { return Lright; };
const point getUl() { return Uleft; };
const point getUr() { return Uright; };
const int getRight() { return Right; };
const int getLeft() { return Left; };
const int getTop() { return Top; };
const int getBottom() { return Bottom; };
private:
point Lleft;
point Lright;
point Uleft;
point Uright;
int Right;
int Left;
int Top;
int Bottom;
};
void rectangle::getArea() {
int width = Right - Left;
int height = Top - Bottom;
std::cout << "The area is " << width * height << ".\n";
};
rectangle::rectangle (point nLl, point nLr, point nUl, point nUr)
{
Lleft = nLl;
Lright = nLr;
Uleft = nUl;
Uright = nUr;
Right = Lright.getx();
Left = Lleft.getx();
Top = Uleft.gety();
Bottom = Lleft.gety();
};
This is Rectangle.cpp:
#include <iostream>
#include "rectangle.hpp"
int main() {
point nnUleft;
nnUleft.setxy(0,2);
point nnUright;
nnUright.setxy(2,2);
point nnLright;
nnLright.setxy(0, 0);
point nnLleft;
nnLleft.setxy(0, 2);
rectangle qd(nnLleft, nnLright, nnUleft, nnUright);
qd.getArea();
char bin;
std::cin >> bin;
std::cout << bin;
}
My problem is that, when compiled, it outputs 0, when it should output 4. How do I make it so that it outputs what it should? Why isn't it working in the first place?
From your code:
Left = 0 (nnuLeft.x)
Right = 0 (nnLright.x)
Top = 2 (nnULeft.y)
Bottom = 2 (nnLleft.y)
so width = 0, Height = 0 so result is 0
So your lower left and lower right need to have different X values.
Likewise your Upper left and Lower left need to need different Y values
Your rectangle is not a real rectangle. Your shape is two lines in your main function.
If you want to get a real rectangle, modify your code.
I modified your code like this:
#include <iostream>
#include "rectangle.hpp"
int main() {
point nnUleft;
nnUleft.setxy(0, 2);
point nnUright;
nnUright.setxy(2, 2);
point nnLright;
nnLright.setxy(2, 0);//here
point nnLleft;
nnLleft.setxy(0, 0);//and here
rectangle qd(nnLleft, nnLright, nnUleft, nnUright);
qd.getArea();
char bin;
std::cin >> bin;
std::cout << bin;
}

Odd behavior of std::vector back()

The following code asserts in the indicated place with "iterator+offset is out of range."
void Network::PushInput(int c, int h, int w) {
Input* input = new Input(batch, c, h, w, data);
layers.push_back(input); // this happens to be the first push_back()
// layers.push_back(input); // doing another doesn't change the assert!
Layer *foo = layers.back(); // asserts here
Layer *baz = layers[layers.size()-1]; // does not assert
}
Input is a public subclass of Layer. layers is declared as
std::vector<Layer *>layers;
If I attempt to duplicate the above with more vanilla template types, e.g., int*, back() works as expected with no asserts. Somehow, the template type matters here. (Note: _ITERATOR_DEBUG_LEVEL is 2, which triggers that assert check in the vector class.)
I'd rather not bluntly change all of the back()'s in the code to size()-1, but would rather understand what is going on here.
Any ideas? (I'll continue to perturb the code until I can find the apparent cause of this, but hopefully this will be obvious to someone else.)
(I'm using Visual Studio 2013 Community Edition, if that matters.)
.....
Here's a stand-alone file that compiles that shows the problem:
#include <vector>
using namespace std;
namespace layer {
class Layer {
public:
Layer(float alpha = 0, float momentum = 0.9f, float weight_decay = 0);
virtual ~Layer();
// three virtual method that all layers should have
virtual void forward(bool train = true) = 0;
virtual void backward() = 0;
virtual void update() = 0;
void adjust_learning(float scale); // change the learning rate
Layer* prev; // previous layer
Layer* next; // next layer
float* data; // X': output (cuDNN y)
int batch; // n: batch size
float alpha; // learning rate
float momentum; // beta: momentum of gradient
float weight_decay; // gamma: weight decay rate
};
} /* namespace layer */
namespace layer {
Layer::Layer(float alpha_, float momentum_, float weight_decay_)
{
std::memset(this, 0, sizeof(*this));
alpha = alpha_;
momentum = momentum_;
weight_decay = weight_decay_;
}
Layer::~Layer() {}
void Layer::adjust_learning(float scale) {
alpha *= scale;
}
}
namespace layer {
class Input : public Layer {
public:
Input(int n, int c, int h, int w, float* _data);
virtual ~Input();
void forward(bool train = true);
void backward();
void update();
};
}
namespace layer {
Input::Input(int n, int c, int h, int w, float* _data) : Layer() {
prev = NULL;
batch = n;
data = _data;
}
Input::~Input() {
data = NULL;
}
void Input::forward(bool train) {
// nothing
}
void Input::backward() {
// nothing
}
void Input::update() {
// nothing
}
}
using namespace layer;
namespace model {
class Network {
private:
std::vector<Layer*> layers; // list of layers
bool has_input, has_output; // sanity check
float* data; // input on device
int batch; // whole size of data, batch size
public:
Network(int batch_size);
virtual ~Network();
void PushInput(int c, int h, int w);
};
}
namespace model {
void Network::PushInput(int c, int h, int w) {
Input* input = new Input(batch, c, h, w, data);
layers.push_back(input);
Layer *foo = layers.back(); // **WHY DOES THIS ASSERT??**
}
Network::Network(int _batch) {
std::memset(this, 0, sizeof(*this));
batch = _batch;
}
Network::~Network() {
for (Layer* l : layers)
delete l;
}
}
void main()
{
model::Network foo(10);
foo.PushInput(2, 3, 4);
}
You have undefined behavior in your code.
In the Layer constructor you do
std::memset(this, 0, sizeof(*this));
The problem with this is that the above call will clear the virtual function table (which is a part of the object) as well. Any virtual function called after that will not work as expected, if at all. That includes the destruction of the objects as the destructors are virtual.

matrix in a class in C++

the following code is for three classes , class One, class Two, class Three.
class Three takes tow vectors, the first vector contains instances of One , the second vector contains instances of Two.
I want to get a 2D matrix via a method in Three , this matrix will have two equal indices each one is the size of the vector of One instances.
I don't know where to declare this matrix , and how to initialize it.
i will present a code is working fine before i declare the matrix , then i will present one example of my many tries which is not working and producing error messages.
here is the code before declaring the matrix(it works fine)
#include<iostream>
#include<vector>
#include <stdlib.h>
using namespace std;
const unsigned int N = 5;
class One
{
private:
unsigned int id;
public:
unsigned int get_id(){return id;};
void set_id(unsigned int value) {id = value;};
One(unsigned int init_val = 0): id(init_val) {}; // constructor
~One() {}; // destructor
};
class Two
{
private:
One first_one;
One second_one;
unsigned int rank;
public:
unsigned int get_rank() {return rank;};
void set_rank(unsigned int value) {rank = value;};
unsigned int get_One_1(){return first_one.get_id();};
unsigned int get_One_2(){return second_one.get_id();};
Two(const One& One_1 = 0, const One& One_2 =0 , unsigned int init_rank = 0)
: first_one(One_1), second_one(One_2), rank(init_rank)
{
}
~Two() {} ; // destructor
};
class Three
{
private:
std::vector<One> ones;
std::vector<Two> twos;
public:
Three(vector<One>& one_vector, vector<Two>& two_vector)
: ones(one_vector), twos(two_vector)
{
}
~Three() {};
vector<One> get_ones(){return ones;};
vector<Two> get_twos(){return twos;};
void set_ones(vector<One> vector_1_value) {ones = vector_1_value;};
void set_twos(vector<Two> vector_2_value) {twos = vector_2_value;};
};
int main()
{
cout<< "Hello, This is a draft for classes"<< endl;
vector<One> elements(5);
cout<<elements[1].get_id()<<endl;
vector<Two> members(10);
cout<<members[8].get_One_1()<<endl;
Three item(elements, members);
cout<<item.get_ones()[3].get_id() << endl;
return 0;
}
now i declared a method to produce a matrix in Three , the method's name is get_Mat() here is the code :
#include<iostream>
#include<vector>
#include <stdlib.h>
using namespace std;
const unsigned int N = 5;
class One
{
private:
unsigned int id;
public:
unsigned int get_id(){return id;};
void set_id(unsigned int value) {id = value;};
One(unsigned int init_val = 0): id(init_val) {}; // constructor
~One() {}; // destructor
};
class Two
{
private:
One first_one;
One second_one;
unsigned int rank;
public:
unsigned int get_rank() {return rank;};
void set_rank(unsigned int value) {rank = value;};
unsigned int get_One_1(){return first_one.get_id();};
unsigned int get_One_2(){return second_one.get_id();};
Two(const One& One_1 = 0, const One& One_2 =0 , unsigned int init_rank = 0)
: first_one(One_1), second_one(One_2), rank(init_rank)
{
}
~Two() {} ; // destructor
};
class Three
{
private:
std::vector<One> ones;
std::vector<Two> twos;
public:
Three(vector<One>& one_vector, vector<Two>& two_vector)
: ones(one_vector), twos(two_vector)
{
}
~Three() {};
vector<One> get_ones(){return ones;};
vector<Two> get_twos(){return twos;};
void set_ones(vector<One> vector_1_value) {ones = vector_1_value;};
void set_twos(vector<Two> vector_2_value) {twos = vector_2_value;};
unsigned int get_Mat() {
unsigned int mat[ones.size()][ones.size()];
for(unsigned int i = 0; i < ones.size(); ++i)
for(unsigned int j = 0; j < ones.size(); ++j)
mat[i][j] = 1;
return mat;}
};
int main()
{
cout<< "Hello, This is a draft for classes"<< endl;
vector<One> elements(5);
cout<<elements[1].get_id()<<endl;
vector<Two> members(10);
cout<<members[8].get_One_1()<<endl;
Three item(elements, members);
cout<<item.get_ones()[3].get_id() << endl;
return 0;
}
I will be very thankful if you can help me to find a way to produce this matrix via a method in class Three.
Thanks.
get_Mat returns an integer, not a matrix. It is better to use vector<vector<unsigned int> >, that will avoid a lot of troubles later on.
Or have a look here (c++):
Return a 2d array from a function
or here (C):
Return a 2d array from a function