Confused with variables in classes - c++

I'm a bit confused with classes was hoping some one could explain.
I have a class I'm making to create buttons for a game menu. There are four variables:
int m_x
int m_y
int m_width
int m_height
I then want to use a render function in the class but Im not understanding how i use the 4 int variables in the class and pass it to the function in the class?
My class is like this:
class Button
{
private:
int m_x, m_y; // coordinates of upper left corner of control
int m_width, m_height; // size of control
public:
Button(int x, int y, int width, int height)
{
m_x = x;
m_y = y;
m_width = width;
m_height = height;
}
void Render(SDL_Surface *source,SDL_Surface *destination,int x, int y)
{
SDL_Rect offset;
offset.x = x;
offset.y = y;
SDL_BlitSurface( source, NULL, destination, &offset );
}
} //end class
Where i am confused is how the values created in public:Button is passed to void render I'm not fully sure I've got this right, if i have its pure luck so far because I'm still a little bit confused.

Maybe an example will help:
#include <iostream>
class Button
{
private:
int m_x, m_y; // coordinates of upper left corner of control
int m_width, m_height; // size of control
public:
Button(int x, int y, int width, int height) :
//This is initialization list syntax. The other way works,
//but is almost always inferior.
m_x(x), m_y(y), m_width(width), m_height(height)
{
}
void MemberFunction()
{
std::cout << m_x << '\n';
std::cout << m_y << '\n';
//etc... use all the members.
}
};
int main() {
//Construct a Button called `button`,
//passing 10,30,100,500 to the constructor
Button button(10,30,100,500);
//Call MemberFunction() on `button`.
//MemberFunction() implicitly has access
//to the m_x, m_y, m_width and m_height
//members of `button`.
button.MemberFunction();
}

You might want to spend some time learning C++ before getting too deep into a complex programming project.
To answer your question, The variables initialized in the constructor (Button) are part of the class instance. So they're available within any class method, including Render.

Related

Assigning a variable within a class with value of a method

Is there a way to assign a variable within a class with a value of a class method?
I was trying the example below, but it is obviously not working. Is there a correct way of doing this?
#include <iostream>
using namespace :: std;
class rectangle
{
public:
rectangle(double h, double w) {
height = h;
width = w;
};
double area(void) {
return height*width;
};
double myarea = (*this).area();
private:
double height, width;
};
int main(void) {
rectangle r(2.5, 3);
cout << "Area is: " << r.area() << endl;
cout << "Area is: " << r.myarea << endl;
return 0;
}
result
Area is: 7.5
Area is: 0
The problem is that member variables are initialized in the order they are declared within the class. Also, your constructor creates the object before you have actually initialized width and height, as you do your initial assignment in the body of the constructor, rather than in an initializer list. Thus, when myarea is initialized (in your code), width and height have not yet been set.
To fix this, you can re-order the members and move the initialization of width and height into a list:
class rectangle {
private:
double height, width; // These will NOW be set before "myarea" is calculated
public:
rectangle(double h, double w) : height{ h }, width{ w } {
// Any assignments done here will be AFTER initialization of "myarea"
}
double area(void) {
return height * width;
}
double myarea = area();
};
Also, you don't need the complex (*this).area() syntax - just area() will do.
EDIT: Another thing to remember is that the setting of myarea by calling the area() function will only be done once (at object creation); if you change either width or height later, you won't (automatically) change myarea.

C++ implicitly transform trivially constructable struct to member

I feel that its unlikelier than not, but I'd like to see if a function can deduce its parameters from a trivially wrapped struct. For example:
struct wrapped_float
{
float f;
wrapped_float(float f) : f(f) {}
};
float saxpy(float a, float x, float y)
{
return a * x + y;
}
int main()
{
wrapped_float a = 1.1, x = 2.2, y = 3.3;
auto result = saxpy(a, x, y); // ofc compile error
}
The motivation behind this is to make a lightweight wrapper around GDI calls with device context handles (HDC). There exists a lot of legacy code which uses HDCs and I'd like to refactor a lot of this code incrementally. My strategy is to make a lightweight wrapper around HDC like this:
#include <Windows.h>
struct graphics
{
HDC dc;
graphics(HDC dc) : dc(dc) {}
void rectangle(int x, int y, int w, int h)
{
Rectangle(dc, x, y, x + w, y + h);
}
};
void OnPaint(HDC dc)
{
Rectangle(dc, 1, 2, 3, 4);
}
int main()
{
HDC dc;
// setup dc here
graphics g = dc;
OnPaint(g);
}
So that if g can be implicitly transformed to HDC, then all legacy code will normally compile, but I can slowly refactor code to become like this:
void OnPaint(graphics g)
{
g.rectangle(1, 2, 3, 4);
}
Any recommendations are also welcome since this simply might not be possible in C++ (or any programming language).
From the comments, I was not aware that C++ had a casting operator. The simple solution is to add:
struct graphics
{
HDC dc;
graphics(HDC dc) : dc(dc) {}
void rectangle(int x, int y, int w, int h)
{
Rectangle(dc, x, y, x + w, y + h);
}
operator HDC()
{
return dc;
}
};

create object with proporties

How to create an object in C++ with proporties?
If the object is an rectangle I want to access the height and the width like this
int height = obj.height;
int width = obj.width;
The object is returned by a function.. So what is the return type of the function?
Create a class Rectangle:
class Rectangle {
private:
int height;
int width;
public:
Rectangle(int h, int w) : height(h), width(w) {} // constructor to initialize width and height
void getHeight() { return height; } // public getters but private attributes to stick to the encapusaltion
void getWidth() { return width; }
};
Have a function returning a rectangle:
Rectangle doSomething() { // the return type is an instance of the class Rectangle
Rectangle r(2, 3); // create a rectangle with a height of 2 and a width of 3
return r; // return the created object
}
int main()
{
Rectangle r = doSomething(); // call your function
cout << r.getHeight() << " " << r.getWidth() << endl; // prompt width and height
}
If you want to access width and height via r.width and r.height change the access specifier private to public. Then you will not need the getters anymore.

C++ Vector Size is Zero

I am trying to create a function that renders everything in a vector of displayobject objects (on another thread). I am using SDL thread.
Here is the displayobject.h:
class DisplayObject
{
protected:
int width;
int height;
int x;
int y;
SDL_Texture* texture;
SDL_Renderer* renderer;
public:
~DisplayObject();
int getX();
void setX(int x);
int getY();
void setY(int y);
int getWidth();
void setWidth(int width);
int getHeight();
void setHeight(int height);
SDL_Texture* getTexture();
SDL_Renderer* getRenderer();
};
In graphics.h I have these variables:
std::vector<DisplayObject> imgArr;
SDL_Thread* renderThread;
static int renderLoop(void* vectorPointer);
This code is in the graphics constructor:
TextLabel textLabel(graphics->getRenderer(), 300, 80, "Hallo Welt", 50, Color(255, 0, 255), "Xenotron.ttf");
//TextLabel inherits from DisplayObject
imgArr.push_back(textLabel);
renderThread = SDL_CreateThread(Graphics::renderLoop, "renderLoop", &imgArr);
This is the render loop function:
int Graphics::renderLoop(void* param)
{
int counter = 0;
bool rendering = true;
std::vector<DisplayObject>* imgArr = (std::vector<DisplayObject>*)param;
while (rendering)
{
cout << imgArr->size() << endl;
counter++;
if (counter > 600)
{
rendering = false;
}
SDL_Delay(16);
}
return 0;
}
The problem is that it only prints 0's in the console. Why does it do that? It is supposed to write 1 since I pushed on object into it.
When you insert a TextLabel into std::vector<DisplayObject>, what is stored in the vector is not your original TextLabel object, but a DisplayObject copy-constructed from the TextLabel. What you want to do is create your TextLabels with new, store pointers to them, and call delete when you no longer need them.
The best solution would be to use boost::ptr_vector<DisplayObject> instead - it will automatically call delete when you erase objects from it.
http://www.boost.org/doc/libs/1_57_0/libs/ptr_container/doc/ptr_container.html
If you can't use Boost, but can use C++11, you can use std::vector<std::unique_ptr<DisplayObject>>.

using operators inside class or struct?

OK so I am working on some game logic, I have done a fair bit of research (as much as the internet will allow) and still don't have a solid understanding of class and struct so please go gentle!
Basically, I want to be able to create an object with the properties all on one line ie.
object a{1, 1, 50, 15, 5}; // create object a
and I want some extra stuff to be made up aswell like:
class object
{
public:
int x;
int y;
int h;
int w;
int s;
int x1;
int y1;
int ps;
int ns;
int x1 = x + w;
int y1 = y + h;
int ps = 0 + s;
int ns = 0 - s;
};
I don't know which language you're working with, but it looks a bit like C++, so here's an example:
class Rect
{
public:
int x, y;
int w, h;
int right, bottom;
// This method is called a constructor.
// It allows you to perform tasks on
// the instantiation of an object.
Rect(int x_, int y_, int w_, int h_)
{
// store geometry
this->x = x_;
this->y = y_;
this->w = w_;
this->h = h_;
// calculate sides
this->right = x_ + w_;
this->bottom = y_ + h_;
}
};
// You use the constructor in your main() function like so:
Rect myObject(1, 1, 50, 15);
// And you can access the members like so:
myObject.x = 10;
myObject.right = myObject.x + myObject.w;
You cannot use operators inside the definition of a class as you proposed in your question. Operations on variables must take place inside a constructor (or other method).