Initialization of const array in C++ [duplicate] - c++

This question already has answers here:
initialize a const array in a class initializer in C++
(10 answers)
Closed 9 years ago.
I need to initialize a const int array in a class constructor via initialization list in C++.
I know that there is an easy solution of this problem based on using
extended initialization list.
Still, I want to avoid using -std=c++11 or -std=gnu++11.
Obviously, I know from the beginning that its size is 4 and the
content is {1, 2, 3, 4}.

The only way I can conceive doing this while staying out of the C++11 initializer list realm is to bury it in a struct wrapper and value-initialize it in your construct-initializer list:
#include <iostream>
using namespace std;
struct ArrayWrap
{
int content[4];
int& operator [](size_t n) { return content[n]; }
int operator [](size_t n) const { return content[n]; }
};
static const ArrayWrap content = { {1,2,3,4} };
struct MyObj
{
const ArrayWrap arrwrap;
MyObj() : arrwrap(content) {}
};
int main(int argc, char *argv[])
{
MyObj obj;
for (int i=0;i<4;++i)
cout << obj.arrwrap[i] << ' ';
cout << endl;
return EXIT_SUCCESS;
}
Output
1 2 3 4
It is common in C to bury fixed arrays in structures when returning them from functions by value, and in this case I'm simply exploiting the default copy-ctor of the wrapper struct as-generated by the C++ compiler.
Probably not the ideal solution for what you want, but it does work, and compiles under C++98.

Well, if you're banning C++11 solutions from the candidate set, then you simply cannot do this.

Related

Why do i get "invalid use of non-static data member" error when i try to create an array inside class? [duplicate]

This question already has answers here:
Array initialization use const variable in C++
(4 answers)
Closed 3 years ago.
I created an array with the length of x but I get the error
invalid use of non-static data member Test::x.
I tried to replace int newArray[x]; with int newArray = new int[x]; but still didn't work out.
When I declared the newArray[x] in the constructor or put static const before int x = 10, the code run successfully.
Why is that?
#include <iostream>
#include <vector>
using namespace std;
class Test
{
private:
int x = 10;
int newArray[x];
public:
Test();
~Test();
};
int main()
{
return 0;
}
int newArray[x]; won't work because size of a static array needs to be known at compile time. Adding static constexpr to the declaration of x makes it a compile time constant and that's why the code compiles.
int newArray = new int[x]; won't work either, because operator new returns a pointer, which cannot be assigned to an integer. Having said that, consider using std::vector instead.

How can I re-define + operator? [duplicate]

This question already has answers here:
Can we overload operators for built-in types like int or float?
(3 answers)
Closed 7 years ago.
I would like to re-define
+
operator.
So, I make a simple code like below code.
int operator+(const int &a, const int &b)
{
int temp = a-b;
return temp;
}
int main()
{
int a = 10;
int b = 5;
cout << a+b << endl;
}
I can re-define with Class type... But I don't want to use Class.
How can I resolve this issue?
You cannot define the operators for plain old data types like int.
You could build your own int class (my_int, say) and include the line #define int my_int. But this would be extremely pernicious and wouldn't work with compile-time evaluated literal expressions.
You cannot redefine operator for int (or any other built in type).
If you say, what do you want to do, we might find some solution.

function that returns an array of objects

I have got a structure
class pyatno {
int pyatnoNumber;
int locX, locY;
bool possible;
char *number;
char pyatnoView[4][4];
}
the idea is to make a function, that would return an array of pyatno.pyatnoView objects, but there is a mess. I don't understand how exactly I can get access to this "property". I am not strong in c++, so if it isn't real, or i am talking something wrong, explain please, cause I am really stacked in this question.
As you mentioned that you are not very strong with c++, and your question is rather unclear, here are several suggestions.
To get access to a class's attributes, c++ has the notion of visibility; The default visibility is private, that is, attributes and functions will not be visible outside of the class:
class Foo {
int some_value;
};
There are several ways you can retrieve data from an object, however to put it simply, you should either make the attribute public:
class Foo {
public:
int some_value;
};
or expose it via accessors/mutators:
class Foo {
int some_value;
public:
int get_some_value() { return some_value; }
void set_some_value(int v) { some_value = v; }
};
Another thing to note is that you can not return arrays! In c++, when an array passes a function boundary (that is to say, passed as a parameter to, or returned from), and in a lot of other cases, an array will 'decay' in to a pointer. For example, the following is how I would pass an array of characters (otherwise known as a c-string) to a function:
#include <iostream>
using namespace std;
void print_cstr(const char *cstr) {
cout << cstr << endl;
}
int main() {
const char my_cstr[20] = "foo bar baz qux";
print_cstr(my_cstr);
return 0;
}
So what happens for N-dimensional arrays? Well, if char[1] decays to char*, then char[1][1] will decay to char**, and so on. You might have noticed this with the older main signature in C programs, which is used to pass an array of strings representing arguments passed to the program:
int main(int argc, char **argv) { ... }
It is very important that you realise that this really is no longer an array. C style strings are a bit special, in that they are conventionally terminated with a null byte \0, which means that you can usually tell where the end of the string is, or how long it is. However, you no longer have any information on how long the array is! For example, this is completely legal:
#include <iostream>
using namespace std;
void bad_fn(const int *nums) {
for (unsigned i = 0; i < 20; ++i) {
cout << "num " << i << " = " << nums[i] << endl;
}
}
int main() {
const int my_nums[5] = { 1, 2, 3, 4, 5, };
bad_fn(my_nums);
return 0;
}
Your function will end up reading memory beyond the bounds of the array, as it has no way of knowing where the array begins or ends (after all, array indexes are just pointer arithmetic). If you do not want to have to worry about keeping track of, and passing around the length of your array (and I would suggest that you do not!), please look at using one of the C++ standard library's containers. std::vector and std::array are two examples that would fit in the use case you have provided, and you can find decent documentation for them here.

Impossible C++ array indexing [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
In C arrays why is this true? a[5] == 5[a]
Accessing arrays by index[array] in C and C++
I just found what seems to be a bug in my code, but not only it compiles, it also works as expected initially...
Consider the following code snipet:
#include <string>
#include <iostream>
using namespace std;
class WeirdTest
{
public:
int value;
string text;
WeirdTest() : value(0),
text("")
{}
virtual ~WeirdTest()
{}
void doWeirdTest()
{
value = 5;
string name[] =
{
"Zero",
"One",
"Two",
"Three",
"Four",
"Five"
};
text = value[name];
cout << "text: " << text << endl;
}
};
int main(int argc, char** argv)
{
WeirdTest test;
test.doWeirdTest();
return 0;
}
Instead of having text=value[name]; it should have been text=name[value]; but the compiler does not complain, and the resulting binary code is the exact same whether the "bug" is here or not.
I'm compiling using g++ 4.6.3, and if someone know what is going on here I would be very grateful. Could it be something in the standard that I missed ? Automatic bug-fix in C++0x maybe ? ;)
Thanks a lot,
Cheers !
Yes, that's a curious "feature". Actually what happens is that the compiler translates the a[i] into *(a + i), so array index and array address are actually interchangeable.
Note, it's valid only if operator [] isn't overloaded.

error C2234: arrays of references are illegal [duplicate]

This question already has answers here:
Why are arrays of references illegal?
(14 answers)
Closed 8 years ago.
I write a code like this:
void Print(const int & dataArray[], const int & arraySize) { // problem
for(int i = 0; i<arraySize; i++) {
cout << dataArray[i] << " ";
}
cout << endl;
}
in mian() function:
`
int iArray[14] = { 7, 3, 32, 2, 55, 34, 6, 13, 29, 22, 11, 9, 1, 5 };
int numArrays = 14;
Print(iArray, numArrays);
....
`
the compiler says that arrays of references are illegal, why it is illegal ??
I see the <effective c++>, it says recommend we use the const and reference, I just try to implement it(I'm a beginner), I also want to know in the void Print(const int dataArray[], const int & arraySize) parameter I use const, & to qualify the arraySize, is it right?(or is it much better than int arraySize or const int arraySize?), I want also use const,& to dataArray[], but I failed.
An array requires its elements to be default-constructible and references are not, hence array of references are illegal. This:
const int & dataArray[]
is an array of references. If you want a reference to an array instead you need this:
const int (&dataArray)[]
Pedantically, the reason why arrays of references are illegal is because the Standard explicitly forbids them.
C++03:8.3.2/4
There shall be no references to references, no arrays of references,
and no pointers to references.
Emphasis mine.
One reason the Standard explicitly forbids arrays of references (maybe there are more) is because of how arrays are indexed. Suppose you do:
Gizmo& gizmos[] = {...};
Gizmo&* g3 = &gizmos[2];
There are several things wrong here. First you have a pointer to a reference, which is illegal. Second, in order to evaluate gizmos[2] the compiler must do an implicit conversion-to-pointer, and then do pointer arithmetic based on that. How big is a Gizmo&?
According to the Standard, the sizeof a reference is, itself, unspecified. However when sizeof is applied to a reference, the result is the size of the referred-to type.
C++03:5.3.3/2 Sizeof
When applied to a reference or a reference type, the result is the
size of the referenced type.
Try running this code and see what happens:
#include <iostream>
#include <iomanip>
using namespace std;
struct Gizmo { int n_[100]; };
int main()
{
typedef Gizmo& GR;
size_t n = sizeof(GR);
cout << n << endl;
}
When I run this on my machine, (MSVC10, Win7x64), the result is 400.
This is why arrays of references are illegal.