Call constructor from other method in C++ - c++

I am not sure is that legal or not in C++:
class Image
{
Image(int w, int h) // constructor
{
...
}
Image GetSpecialImage()
{
Image rVal(10,10);
return rVal;
}
}
Do I need to use another middle level init() method to do this in C++? If yes, can you please show me how?
EDIT: Eventhough you say it's fine, it does not really do what I want to do... Let me give you some more code:
class Image
{
float* data;
int w;
int h;
Image(int w, int h) // constructor
{
this->w = w;
this->h = h;
data = (float*) malloc ( w * h * sizeof(float) );
}
Image GetSpecialImage()
{
Image rVal(this->w,this->h);
for(i=0;i<this->w * this->h;i++)
{
rVal.data[i] = this->data[i] + 1;
}
return rVal;
}
}
int main()
{
Image temp(100, 100);
Image result = temp.GetSpecialImage();
cout<<result.data[0];
return 0;
}
Is there anything wrong with this part?

As Seth said, that is legal.
Something you could change to make it work even better is to make GetSpecialImage a static function. A static function defined in a class is a class function instead of an object function. That means you don't need an object in order to call it.
It would then be called like this: Image special = Image::GetSpecialImage();

Yes, you can do this. I would just do this though
Image GetSpecialImage()
{
return Image(10,10);
}

While there's nothing wrong with this code (well, except for returning a local, which is a no-no), I guess what you're looking for is a static constructor pattern. Like so:
class Image{
public:
static Image* GetSpecialImage(){
return new Image(10,10);
}
};
//and call it so
Image *i = Image::GetSpecialImage();

Related

Using halide with HDR images represented as float array

that's my first post here so sorry if I do something wrong:). I will try to do my best.
I currently working on my HDR image processing program, and I wonna implement some basing TMO using Halide. Problem is all my images are represented as float array (with order like: b1,g1,r1,a1, b2,g2,r2,a2, ... ). Using Halide to process image require Halide::Image class. Problem is I don't know how to pass those data there.
Anyone can help, or have same problem and know the answer?
Edit:
Finally got it! I need to set stride on input and output buffer in generator. Thx all for help:-)
Edit:
I tried two different ways:
int halideOperations( float data[] , int size, int width,int heighy )
{
buffer_t input_buf = { 0 };
input_buf.host = &data[0];
}
or:
int halideOperations( float data[] , int size, int width,int heighy )
{
Halide::Image(Halide::Type::Float, x, y, 0, 0, data);
}
I was thinking about editing Halide.h file and changing uint8_t * host to float_t * host but i don't think it's good idea.
Edit:
I tried using code below with my float image (RGBA):
AOT function generation:
int main(int arg, char ** argv)
{
Halide::ImageParam img(Halide::type_of<float>(), 3);
Halide::Func f;
Halide::Var x, y, c;
f(x, y, c) = Halide::pow(img(x,y,c), 2.f);
std::vector<Halide::Argument> arguments = { img };
f.compile_to_file("function", arguments);
return 0;
}
Proper code calling:
int halideOperations(float data[], int size, int width, int height)
{
buffer_t output_buf = { 0 };
buffer_t buf = { 0 };
buf.host = (uint8_t *)data;
float * output = new float[width * height * 4];
output_buf.host = (uint8_t*)(output);
output_buf.extent[0] = buf.extent[0] = width;
output_buf.extent[1] = buf.extent[1] = height;
output_buf.extent[2] = buf.extent[2] = 4;
output_buf.stride[0] = buf.stride[0] = 4;
output_buf.stride[1] = buf.stride[1] = width * 4;
output_buf.elem_size = buf.elem_size = sizeof(float);
function(&buf, &output_buf);
delete output;
return 1;
}
unfortunately I got crash with msg:
Error: Constraint violated: f0.stride.0 (4) == 1 (1)
I think something is wrong with this line: output_buf.stride[0] = buf.stride[0] = 4, but I'm not sure what should I change. Any tips?
If you are using buffer_t directly, you must cast the pointer assigned to host to a uint8_t * :
buf.host = (uint8_t *)&data[0]; // Often, can be just "(uint8_t *)data"
This is what you want to do if you are using Ahead-Of-Time (AOT) compilation and the data is not being allocated as part of the code which directly calls Halide. (Other methods discussed below control the storage allocation so they cannot take a pointer that is passed to them.)
If you are using either Halide::Image or Halide::Tools::Image, then the type casting is handled internally. The constructor used above for Halide::Image does't exist as Halide::Image is a template class where the underlying data type is a template parameter:
Halide::Image<float> image_storage(width, height, channels);
Note this will store the data in planar layout. Halide::Tools::Image is similar but has an option to do interleaved layout. (Personally, I try not to use either of these outside of small test programs. There is a long term plan to rationalize all of this which will proceed after the arbitrary dimension buffer_t branch is merged. Note also Halide::Image requires libHalide.a to be linked where Halide::Tools::Image does not and is header file only via including common/halide_image.h .)
There is also the Halide::Buffer class which is a wrapper on buffer_t that is useful in Just-In-Time (JIT) compilation. It can reference passed in storage and is not templated. However my guess is you want to use buffer_t directly and simply need the type cast to assign host. Also be sure to set the elem_size field of buffer_t to "sizeof(float)".
For an interleaved float buffer, you'll end up with something like:
buffer_t buf = {0};
buf.host = (uint8_t *)float_data; // Might also need const_cast
// If the buffer doesn't start at (0, 0), then assign mins
buf.extent[0] = width; // In elements, not bytes
buf.extent[1] = height; // In elements, not bytes
buf.extent[2] = 3; // Assuming RGB
// No need to assign additional extents as they were init'ed to zero above
buf.stride[0] = 3; // RGB interleaved
buf.stride[1] = width * 3; // Assuming no line padding
buf.stride[2] = 1; // Channel interleaved
buf.elem_size = sizeof(float);
You will also need to pay attention to the bounds in the Halide code itself. Probably best to look at the set_stride and bound calls in tutorial/lesson_16_rgb_generate.cpp for information on that.
In addition to Zalman's answer above you also have to specify the strides for the inputs and outputs when defining your Halide function like below:
int main(int arg, char ** argv)
{
Halide::ImageParam img(Halide::type_of<float>(), 3);
Halide::Func f;
Halide::Var x, y, c;
f(x, y, c) = Halide::pow(img(x,y,c), 2.f);
// You need the following
f.set_stride(0, f.output_buffer().extent(2));
f.set_stride(1, f.output_buffer().extent(0) * f.output_buffer().extent(2));
img.set_stride(0, img.extent(2));
img.set_stride(1, img.extent(2) *img.extent(0));
// <- up to here
std::vector<Halide::Argument> arguments = { img };
f.compile_to_file("function", arguments);
return 0;
}
then your code should run.

How to use of "new" for polygons in C++

The definitions of Circle and Polygon are here in Graph.h and graph.cpp.
For some exercise I need to have some unnamed shapes which are made using the new keyword. Both Circle and polygon are kinds of Shape.
For example if I have a vector_ref<Circle> vc; I can using this statement add an unnamed Circle into that vector: vc.push_back(new Circle (Point (p), 50)); because I can supply parameters (which are a point and a radius) of a circle when defining it.
But for polygons the subject is different.
For having a polygon I must declare it first, e.g., Polygon poly; then add points to it, this way, poly.add(Point(p));. Now it has caused a problem for me.
Consider I have a vector of polygons, Vector_ref<Polygon> vp; Now how to add (that is push back) a polygon using the new keyword just like I did for circle please?
My code is this:
#include <GUI.h>
using namespace Graph_lib;
//---------------------------------
class Math_shapes : public Window {
public:
Math_shapes(Point, int, int, const string&);
private:
//Widgets
Menu menu;
Button quit_button;
In_box x_coor;
In_box y_coor;
Vector_ref<Circle> vc;
Vector_ref<Graph_lib::Rectangle> vr;
Vector_ref<Graph_lib::Polygon> vt;
Vector_ref<Graph_lib::Polygon> vh;
//Action fucntions
void circle_pressed() {
int x = x_coor.get_int();
int y = y_coor.get_int();
vc.push_back(new Circle (Point(x,y), 50));
attach(vc[vc.size()-1]);
redraw();
}
void square_pressed() {
int x = x_coor.get_int();
int y = y_coor.get_int();
vr.push_back(new Graph_lib::Rectangle (Point(x,y), Point(x+100,y+100)));
attach(vr[vr.size()-1]);
redraw();
}
void triangle_pressed() {
int x = x_coor.get_int();
int y = y_coor.get_int();
vt.push_back(new Graph_lib::Polygon); // Problem is here!!
attach(vt[vt.size()-1]);
redraw();
}
void hexagon_pressed() {
int x = x_coor.get_int();
int y = y_coor.get_int();
Graph_lib::Polygon h;
h.add(Point(x,y)); h.add(Point(x+50,y+50)); h.add(Point(x+50,y+80));
h.add(Point(x,y+100)); h.add(Point(x-50,y+80)); h.add(Point(x-50,y+50));
vh.push_back(h);
attach(vh[vh.size()-1]);
redraw();
}
void quit() { hide(); }
// Call-back functions
static void cb_circle (Address, Address pw) { reference_to<Math_shapes>(pw).circle_pressed(); }
static void cb_square (Address, Address pw) { reference_to<Math_shapes>(pw).square_pressed(); }
static void cb_triangle (Address, Address pw) { reference_to<Math_shapes>(pw).triangle_pressed(); }
static void cb_hexagon (Address, Address pw) { reference_to<Math_shapes>(pw).hexagon_pressed(); }
static void cb_quit (Address, Address pw) { reference_to<Math_shapes>(pw).quit(); }
};
//----------------------------------------------------------------------------------
Math_shapes::Math_shapes(Point xy, int w, int h, const string& title):
Window(xy, w, h, title),
menu (Point(x_max()-150,70),120,30,Menu::vertical, "MathShapes"),
quit_button (Point(x_max()-100, 20), 70,20, "Quit", cb_quit),
x_coor(Point(x_max()-450,30),50,20,"x coordinate: "),
y_coor(Point(x_max()-250,30),50,20,"y coordinate: ")
{
attach(x_coor);
attach(y_coor);
attach(quit_button);
menu.attach(new Button(Point(0,0),0,0,"Circle",cb_circle));
menu.attach(new Button(Point(0,0),0,0,"Square",cb_square));
menu.attach(new Button(Point(0,0),0,0,"Equilateral triangle",cb_triangle));
menu.attach(new Button(Point(0,0),0,0,"Hexagon",cb_hexagon));
attach(menu);
}
//-------------------------------------------
int main()
try {
Math_shapes M_s(Point(100,100), 800, 600, "Math Shapes");
return gui_main();
}
catch(...)
{
return 0;
}
You simply need to hold a pointer to your polygon until you've put it in the conatiner:
Circle* pPoly = new Polygon();
// ...
pPoly->add(Point(p1));
// ...
pPoly->add(Point(p2));
// ...
vc.push_back(pPoly);
you probably want to use smart pointers rather than raw ones as above but this is where you can start.
Have you tried this
void triangle_pressed() {
int x = x_coor.get_int();
int y = y_coor.get_int();
Polygon *poly = new Polygon();
poly.add(Point(x));// add your points, I don't know if these are the right points
poly.add(Point(y));// but have you tried this way? creating it, adding, then calling
vt.push_back(poly); // push back without the move
attach(vt[vt.size()-1]);
redraw();
Well, in order to use the new operator, you would need to create a Polygon constructor that takes vector<Point> or initializer_list<Point> as an argument.
The other way around would be to create a helper function, e.g.
-- note that this is really suboptimal, there may be much better solution using move semantics, etc. (or even variadic template function for the matter)
Polygon* make_polygon(initializer_list<Point>& points)
{
Polygon* poly = new Polygon();
for (auto point : points)
poly->Add(point);
return poly;
}
And then just call vp.push_back(make_polygon({p1, p2, ...});
Obviously you could change the function to work without pointers simply by removing them alongside with the new operator call, but then it wouldn't work with your vector_ref<Polygon> type. You would need to use vector<Polygon> instead, as I assume that vector_ref<T> is just a typedef for vector<T*>

Why do I get an EXC_BAD_ACCESS when reading back a private class variable?

I have a Rectangle class shown below:
Header:
class Rectangle: public Polygon {
private:
float _width, _height;
public:
Rectangle(float width, float height);
float getWidth(float* width) const;
float getHeight(float* height) const;
bool isCollidingWith(Rectangle* other) const;
};
Selected Implementation:
Rectangle::Rectangle(float width, float height) : Polygon(explodeRect(width, height, new struct vertex[4]), 4) {
printf("creating rect %f x %f\n", width, height);
_width = width;
_height = height;
printf("set _width to %f\n", _width);
}
float Rectangle::getWidth(float* width) const {
printf("_w: %f\n", _width);
*width = _width;
return *width;
//return (*width = _width);
}
float Rectangle::getHeight(float* height) const {
return (*height = _height);
}
I initialize an instance of the Rectangle class, and the output indicates that the _width variable is being correctly assigned. However, when I later try to read the variable using the getWidth method, I get an EXC_BAD_ACCESS error on the line:
printf("_w: %f\n", _width);
Why can I no longer read this variable? I get the same problem with the _height variable as well.
EDIT: I would also like to note that if I skip reading the width, I get an error trying to read public variables directly from the object, e.g. when I try to read its x position with obj->x.
EDIT 2: Could this be from the fact that the object is an instance of a subclass of Rectangle, and this subclass is defined in a different file than Rectangle is? I am also reading the values from a third file.
EDIT 3: More code below.
I am trying to re-create Tetris with OpenGL. In my display method, I have this code to draw the rectangles:
if(fallingBlock != nullptr) {
printf("drawing falling block at (%f, %f)\n", fallingBlock->x, fallingBlock->y);
draw(fallingBlock);
}
fallingBlock is defined as a global variable at the top of my file:
Block* fallingBlock;
From my main, I call an initVars method that subsequently calls a startDroppingBlock method. Here it is:
void startDroppingBlock() {
Block* block = availableBlocks[random() % numAvailableBlocks].copy();
block->x = 0.5;
block->y = SCREEN_TOP;
block->dy = -0.01f;
//printf("copied block is at (%f, %f)\n", block->x, block->y);
fallingBlock = block;
}
And here is my block drawing method:
void draw(Block* obj) {
bool shape[3][3];
obj->getShape(shape);
//printf("got shape: {%d, %d, %d}, {%d, %d, %d}, {%d, %d, %d}\n", shape[0][0], shape[0][1], shape[0][2], shape[1][0], shape[1][1], shape[1][2], shape[2][0], shape[2][1], shape[2][2]);
/*float pieceWidth;
obj->getWidth(&pieceWidth);
pieceWidth /= 3.0f;*/
float pieceWidth = obj->getWidth();
for(unsigned int i=0; i<3; i++) {
for(unsigned int j=0; j<3; j++) {
if(shape[i][j]) {
Square rect = Square(pieceWidth);
rect.x = obj->x + pieceWidth * j;
rect.y = obj->y + pieceWidth * i;
rect.color = obj->color;
draw(&rect);
}
}
}
}
I get an EXC_BAD_ACCESS error on the line [...]. Why can I no longer read this variable? I get the same problem with the _height variable as well. [later...] I have tried both float pieceWidth; obj->getWidth(&pieceWidth); and obj->getWidth(new float) - the actual error is on the line where I read _width, before I even use the passed in pointer. [later...] I modified the getWidth and getHeight methods to just simply return _width and _height. Now I just get an error on return _width;
In this case I see you are using a Rectangle* pointer as obj->getWidth which can as well lead to a bad access error if obj is not a valid pointer.
It is to note that I don't quite understand your getter method at all. A simplified (and possibly standard) version of it might be:
float Rectangle::getWidth() const {
return _width;
}
With the only difference that when you used:
// float a;
// float b;
a = rect.getWidth(&b);
you can now do:
// float a;
// float b;
a = b = rect.getWidth();
which is possibly cleaner and will surely don't cause such an error. A good rule of thumb is never to use pointers when possible. If you need to modify a variable inside a function just use a reference.

c++: a class accessing an std::vector of main class by pointers goes wrong

I'm building my C++ project with VS2012 Express, Platform Toolset v100, and with openFrameworks 0.7.4.
I have a class called NameRect and this is part of the .h file:
void config(int cx, int cy, int cw, int ch, std::string cname) {
x = cx;
y = cy;
w = cw;
h = ch;
name = cname;
dead = false;
}
void branch(int iterants, std::vector<NameRect> *nrs) {
for (int i = 0; i < iterants; i++) {
NameRect nnr;
nnr.config(x + w, y - iterants * h / 2 + i * h, w, h, "cb");
children.push_back(nnr);
nrs->push_back(nnr);
}
}
void render() {
if (!dead) {
ofSetColor(ofRandom(0, 255), ofRandom(0, 255), ofRandom(0, 255), 0);
ofRect(x, y, w, h);
}
}
And there's the code in my testApp.cpp:
//--------------------------------------------------------------
void testApp::setup(){
ofSetWindowShape(800, 600);
nr.config(0, 300, 50, 10, "cb");
nrs.push_back(nr);
}
//--------------------------------------------------------------
void testApp::update(){
if (ofRandom(0, 50) <= 1 && nrs.size() < 100) {
for (int cnri = 0; cnri < nrs.size(); cnri++) {
if (ofRandom(0, nrs.size() - cnri) <= 1) {
nrs[cnri].branch(2, &nrs);
}
}
}
}
//--------------------------------------------------------------
void testApp::draw(){
for (int di = 0; di < nrs.size(); di++) {
nrs[di].render();
}
}
And when I actually build (succeeds) this project and run it, it gives me such an error:
I take a look at the local variables watch and it shows such large integer values!
What is the problem?
branch() is modifying the vector array which is passed in as the second parameter.
This means when you call nrs[cnri].branch(2, &nrs) from testApp::update() the underlying array structure is modified. This will lead to unpredictable results and will surely cause your access violation.
your problem #1 is nrs[cnri].branch(2, &nrs);, you may be reallocating memory where nrs[cnri] is residing from inside branch() when doing push_back()
your problem #2, which you'll face once you have started including your header to multiple cpp files, is the way you define functions. If you define them in the header put "inline" otherwise you'll have the same function defined in multiple places.

How to create an object inside another class with a constructor?

So I was working on my code, which is designed in a modular way. Now, one of my classes; called Splash has to create a object of another class which is called Emitter. Normally you would just create the object and be done with it, but that doesn't work here, as the Emitter class has a custom constructor. But when I try to create an object, it doesn't work.
As an example;
Emitter has a constructor like so: Emitter::Emitter(int x, int y, int amount); and needs to be created so it can be accessed in the Splash class.
I tried to do this, but it didn't work:
class Splash{
private:
Emitter ps(100, 200, 400, "firstimage.png", "secondimage.png"); // Try to create object, doesn't work.
public:
// Other splash class functions.
}
I also tried this, which didn't work either:
class Splash{
private:
Emitter ps; // Try to create object, doesn't work.
public:
Splash() : ps(100, 200, 400, "firstimage.png", "secondimage.png")
{};
}
Edit: I know the second way is supposed to work, however it doesn't. If I remove the Emitter Section, the code works. but when I do it the second way, no window opens, no application is executed.
So how can I create my Emitter object for use in Splash?
Edit:
Here is my code for the emitter class and header:
Header
// Particle engine for the project
#ifndef _PARTICLE_H_
#define _PARTICLE_H_
#include <vector>
#include <string>
#include "SDL/SDL.h"
#include "SDL/SDL_image.h"
#include "image.h"
extern SDL_Surface* gameScreen;
class Particle{
private: // Particle settings
int x, y;
int lifetime;
private: // Particle surface that shall be applied
SDL_Surface* particleScreen;
public: // Constructor and destructor
Particle(int xA, int yA, string particleSprite);
~Particle(){};
public: // Various functions
void show();
bool isDead();
};
class Emitter{
private: // Emitter settings
int x, y;
int xVel, yVel;
private: // The particles for a dot
vector<Particle> particles;
SDL_Surface* emitterScreen;
string particleImg;
public: // Constructor and destructor
Emitter(int amount, int x, int y, string particleImage, string emitterImage);
~Emitter();
public: // Helper functions
void move();
void show();
void showParticles();
};
#endif
and here is the emitter functions:
#include "particle.h"
// The particle class stuff
Particle::Particle(int xA, int yA, string particleSprite){
// Draw the particle in a random location about the emitter within 25 pixels
x = xA - 5 + (rand() % 25);
y = yA - 5 + (rand() % 25);
lifetime = rand() % 6;
particleScreen = Image::loadImage(particleSprite);
}
void Particle::show(){
// Apply surface and age particle
Image::applySurface(x, y, particleScreen, gameScreen);
++lifetime;
}
bool Particle::isDead(){
if(lifetime > 11)
return true;
return false;
}
// The emitter class stuff
Emitter::Emitter(int amount, int x, int y, string particleImage, string emitterImage){
// Seed the time for random emitter
srand(SDL_GetTicks());
// Set up the variables and create the particles
x = y = xVel = yVel = 0;
particles.resize(amount, Particle(x, y, particleImage));
emitterScreen = Image::loadImage(emitterImage);
particleImg = particleImage;
}
Emitter::~Emitter(){
particles.clear();
}
void Emitter::move(){
}
void Emitter::show(){
// Show the dot image.
Image::applySurface(x, y, emitterScreen, gameScreen);
}
void Emitter::showParticles(){
// Go through all the particles
for(vector<Particle>::size_type i = 0; i != particles.size(); i++){
if(particles[i].isDead() == true){
particles.erase(particles.begin() + i);
particles.insert(particles.begin() + i, Particle(x, y, particleImg));
}
}
// And show all the particles
for(vector<Particle>::size_type i = 0; i != particles.size(); i++){
particles[i].show();
}
}
Also here is the Splash Class and the Splash Header.
The second option should work, and I would start looking at compilation errors to see why it doesn't. In fact, please post any compilation errors you have related to this code.
In the meantime, you can do something like this:
class Splash{
private:
Emitter* ps;
public:
Splash() { ps = new Emitter(100,200,400); }
Splash(const Splash& copy_from_me) { //you are now responsible for this }
Splash & operator= (const Splash & other) { //you are now responsible for this}
~Splash() { delete ps; }
};
Well, I managed to fix it, in a hackish way though. What I did was create a default constructor, and move my normal Constructor code into a new function. Then I created the object and called the the new init function to set everything up.