Creating new structs on the fly - c++

I am (very) new to C++, and am having some issues understanding structs. I'm using example code from a course, so I have:
struct Point {
int x;
int y;
}
In another bit of code, I want to write the following:
drawLine(point1, new Point(x, y));
This does not work, and I understand that I am trying to declare a struct as if it were a class, but is there a way to do this? I have currently written a helper function which returns a Point from an x,y, but this seems roundabout.

The problem isn't that you're trying to declare a struct as if it were a class (in fact, there's very little difference between the two in C++).
The problem is that you're trying to construct a Point from two ints, and there ins't a suitable constructor. Here is how you can add one:
struct Point {
int x;
int y;
Point(int x, int y): x(x), y(y) {}
};

new returns a pointer. Just drawLine(point1, Point(x,y)) should work if you define the appropriate constructor for Point.
(drawLine(point1, *(new Point(x,y))) would also work, but would introduce a memory leak; every new should be balanced by a delete.)

The difference between struct and class in c++ is not that huge. Why don't you add a constructor to your struct?

Related

Writing a struct template with two vectors

What I am trying to achieve is create a template of a struct myVector which would contain two vectors i.e. vector_a and vector_b. But i am quite new to templates. I mean, I know why and when one would prefer using Templates in certain situations but I am not quite sure how to tackle this problem. What I have written is:
'''
#include<iostream>
#include<stddef.h>
#include<vector>
template <typename T> struct myVector {
std::vector<T> vector_a;
std::vector<T> vector_b;
};
int main() {
myVector<int> z1(5);
myVector<int> z2(6);
}
'''
I end up getting errors like no matching function for call to ‘VectorXY::VectorXY(int)’
for the vector VectorXY z2(6);
Therefore, I would really appreciate your help. Thanks in advance.
Your error has nothing to do with templates. Consider the following code
struct Int { int i; };
int main()
{
Int z(1); // doesn't compile
}
and you get the error, no matching constructor Int(int).
Classes are an abstraction over something else. It might seem obvious that an int and an Int in this case are the same thing, and constructing one should be like constructing the other. But the compiler doesn't know that, so you need to provide a constructor that passes the argument onto the member.
struct Int
{
int i;
Int(int n) : i(n) {}
};
Note that in C++20, the compiler will actually be able to figure out that you want to use each constructor argument to initialize the corresponding member of your class, so even without a provided constructor, the Int will work like an int.
However, even in that case, your code would not work, since you need to use more complicated rules to construct your members. In your case, you'll need something like
myVector(int n) : vector_a(n), vector_b(n) {}
Assuming that you want the internal vectors to be constructed with the value passed into the constructor. Based on your calling code, it seems that's what you want, but you can write any logic in the constructor.

How to maintain order of class members and still have a working constructor

I want to have tidy header files, where puiblic members are listed first, then private members.
class A
{
public:
A() : y(0), z(0), x(y + z)
{}
int x;
private:
int y;
int z;
};
Members are initialized in the order they are declared, so this constructor is buggy because y and z are not initialized when x is using them.
This is just an example where I could write x(0), but if these weren't ints but bigger types, then it would be cumbersome.
To get around this I would need to first list privete members y and z,
then public member x.
Is there any way that I can leave my private members at the bottom whilst initializing them first in the initializer list?
If not, please guide me to how I should order members, because I can't find any examples of this online. First listing some public, then some private, then more public members seems dirty to me but maybe I'm wrong.
Using a delegating constructor you can write this as:
class A
{
public:
A() : A(0, 0) { }
{}
int x;
private:
explicit A(int y_, int z_) : x(y_ + z_), y(y_), z(z_) { }
int y;
int z;
};
C++, as a language, doesn't do a great job of keeping implementation details out of header files, or separate from the interface in general. Anything you do here is going to be a compromise.
One hard-line approach would be to not have any public member variables, and for that matter to separate and expose a pure virtual interface (in a separate file). At that point, the actual class wouldn't even need to be in a header -- just in a source file, referred to by a factory function -- so the remaining header is as clean as you'd like. This is not an approach I'd recommend.
In any case, there are various practical considerations in C++ which constrain the order of class members. Putting all the public members at the top of the class is a good plan A, but sometimes it's not going to work out, and I wouldn't suggest that you go to any heroics to make it work out.
Is there any way that I can leave my private members at the bottom whilst initializing them first
No. Members are initialised in order of declaration; there is no way around that.
If you just want the members somewhere other than the top of the class, then you could use a base:
struct B {
int y;
int z;
};
class A : B
{
public:
A() : B{0, 0}, x(y + z)
{}
int x;
};
First listing some public, then some private, then more public members seems dirty to me but maybe I'm wrong.
That's not necesasry in your case, as you can put all private stuff first and then all public. But in general, splitting declarations with same access specifier is just fine; although rarely necessary.
The problem is that X is dependent on Y and Z, but Y and Z are knowns.
Possible ways you could look to solve this:
(1) Pass in a constructed X, instead of having the constructor make it.
int y = 1;
int z = 40;
int x = y + z;
A(y, z, x);
(2) A more wild idea, (please don't do this, it typically indicates a problem with how you've factored your code). Create a default object and then use placement new. However, when I see code like this, it's typically using an init() function or something. It's super overkill for ints, but I'm assuming that you have a more complex type which is why you're doing it.
A() : y(0), z(0), x(/*default construct*/)
{
new (&x) int(y + z);
}
//or
A() : y(0), z(0), x(/*default construct*/)
{
x.init(y, z);
}
Overall, I think you should re-evaluate why X depends on Y and Z, and maybe shuffle some data and responsibilities around.
If X depends on the state of Y and Z, you might want to make it a function instead if it's used outside of the class, because as a public member variable other people could modify it and possible de-sync it from X and Y. You might also want to put Y and Z inside of X instead.

C++ Object vs Struct Memory Overhead

I need to create very large arrays of RGB values for image processing. The actual operations that will be performed on them are simple—just orthogonal projection to see how similar two colors are—but every bit counts with regards to memory. I am thinking about storing images as a double pointer to structs with 3 chars in them, which I thought would be the most memory efficent way, but I know it is usually recommended to use wrapper classes. By question is how trivial is the memory overhead for creating a class vs a struct and using some sort of wrapper vs using a double pointer.
There is absolutely no difference between
class X
{
public:
T1 x;
T2 y;
T3 z;
}
and
struct X
{
T1 x;
T2 y;
T3 z;
};
If you add virtual functions to the class, yes, it will add to the storage. But nothing else will make any difference between class and struct (in fact, it's possible to have virtual members in struct too - although it is typical to distinguish between struct and class by having member functions and (non-trivial) constructors only for classes).

C++ OOP which way is better to give values to constructor

I am currently learning C++ and having some problems understanding on how to give values to the constructor. Got my exercise working but am not sure which way is smartest/best.
Way nr. 1
class Vector2d{
public:
Vector2d(double x, double y):x(x),
y(y)
{
}
and way nr.2
class Vector2d{
public:
void set_values (double,double);
Vector2d()
{
}
void Vector2d::set_values (double a, double b) {
x = a;
y = b;
}
Found both ways by reading some tutorials and both ways are working. I guess the first one is more efficient as I don´t have to write a new void, but I am not exactly sure what
:x(x),
y(y)
is doing/meaning.
Thanks a lot in advance!
In C++ doing it by saying
:x(x),
y(y)
You will actually save instructions when it is compiled. The compiler will actually initialize those variables directly inline when space is made for the class.
So I would say that way is better.
I am not exactly sure what [code...] is doing/meaning.
They are initializing your member variables.
It's probably confusing because your constructor parameters were given the same names. Consider this equivalent:
Vector2d(double x_param, double y_param)
: x(x_param) // initialize member variable "x"
, y(y_param) // initialize member variable "y"
{
}
It's reasonable for your class to have both this constructor, and the set_values function to change the values after construction.
Constructor with parameter is created to initialize the member attributes of the class (your 1st solution) and it is different from default constructor (with no parameters - constructor in your 2nd solution).
In your second solution, you are using a setter (a member function to set the values of member attributes) which we can call anytime we need to set the values but with the constructor with parameters (1st solution), we can only set the values for the first time when we create an object to that class.
For example;
when we create the object;
Vector2d vec2d(2.3, 4.5);
it will set the values of x and y to 2.3 and 4.5 respectively but what will we do if we need to set the values again in the program? We will then use setter function like;
vec2d.set_values(5.0, 7.8);
so in short, we only use what we need according to our scenario. If we don't want to set the values again then constructor with parameters (your 1st solution) is the best.
We do the following
:x(x),
y(y)
to assign the value of x and y coming through parameters in constructor to the class members x and y. It is the same as;
class Vector2d{
public:
Vector2d(double x, double y)
{
//"this" pointer is used to differentiate the variables
this->x = x;
this->y = y;
}
}
or for the simplicity I would suggest to use different names if you don't know about this pointer yet;
class Vector2d{
public:
Vector2d(double a, double b)
{
x = a;
y = b;
}
}
with #1 you are instructing the program to initialize x,y by calling their constructor
with #2 you are calling operator= to overwrite the value of x,y by: the value obatained by calling the two constructors: x.operator=(double(right_value))
doesn't differ much since the type involved is "double", would be much different with some complex classes i guess
First way is calling the constructor to initialize members; second way is calling member function to change the value of member variables by assigning, since you only define default constructor, initially members are initialized with default value, then if you call the set_values function, they are reassigned inside that function body. In the current example, they will have the same effect. But it is usually better to initialize member variables at the constructor's initializer list. Your second way looks like a setter function. You cannot use the second way to initialize class member variables since it is not static.
It is preferrable to use the first way if you are constructing an object.
Using the initializer list, the members are created and initialized only once, with the given value.
If you will use separate function to initialize your object, than between constructor call and initialization, your object will be in unitialized state.
The only case you need it - when really know what are you doing.
And also initializing in constructor is faster. When you write
my_class()
: field_(value)
{
}
your field initialized by copying value into it. In other case it initialized, when copied, which is overhead.

passing structure directly to function

I have a struct that I initialize like this:
typedef struct
{
word w;
long v;
}
MyStruct;
MyStruct sx = {0,0};
Update(sx);
Now, it seems such a waste to first declare it and then to pass it. I know that in C#, there's a way to do everything in one line. Is there any possiblity of passing it in a more clever (read: cleaner) way to my update function?
In C++, structs are the same as classes except in structs everything is public by default. So you can give a struct a constructor, e.g.
struct MyStruct
{
word w;
long v;
MyStruct(word w, long v) : w(w), v(v) {}
};
Update(MyStruct(0,0));
Also, C-style struct typedef'ing is unnecessary and discouraged in C++.
It depends on how your Update is declared. If it expects a value of MyStruct type or a reference of const MyStruct& type, you can just do
Update(MyStruct());
This is possible because you wanted to initialize your object with zeroes (which is what the () initializer will do in this case). If you needed different (non-zero) initializer values, you have to either provide a constructor for MyStruct or do it the way you do it in your question (at least in the current version of the C++ language).