I have to questions the 1st is: How can i initialize an array after declaring it. for example string test[5] then somewhere else in the program how can i do something like this test ??? = {"one", "Two", "three", "Four", "Five"};
my 2nd question is: how can i initialize variable within a class.
any help is greatly appreciated
to initialize a variable within a class, the most common way that i find people do it is within the classes contructor. So take the following code for example:
class someClass
{
public:
someClass();
protected:
int age;
string Name;
};
//option one
someClass::someClass()
{
this -> age = 18;
this -> Name = "Chuck Norris";
}
//option two
someClass::someClass() : age(18), Name("Chuck Norris")
{
}
so as you can see in the above code there are two ways to initialize variables that you declare within a class. The first method is within the constructors brackets and using the "this" keyword (it's optional to use the keyword though, personally i use it) and setting the variables to their appropriate values. The second method is by initializing the variables outside the function definitions name using a colon, and typing the variables name followed by the value of it inside parenthesis.
thanks so much that makes a lot of sence :) i was hoping there would be away to initialize the whole array but oh well. one question now is how could i access the variable age inside of main. thanks again
After declaring an array, you can only assign to it. Initialization must happen during the declaration if at all. Another option is to use a functor, when that makes sense along with an algorithm such as std::generate.
> How can i initialize an array after declaring it
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
// declare the array before it is used (with the extern keyword)
externconst std::string my_array[] ; // declare the array
// note: the size of the array is omitted in the declaration
// it can be specified only when the array is defined
externconst std::size_t my_array_size ; // and also declare the array size
// use them after they have been declared
void foo()
{
for( std::size_t i = 0 ; i < my_array_size ; ++i )
std::cout << my_array[i] << '\n' ;
}
// somewhere in your program, define the array (defining something initializes it)
const std::string my_array[] = { "One", "Two", "three", "Four", "Five" } ;
// and also define the array size
const std::size_t my_array_size = sizeof(my_array) / sizeof(my_array[0]) ;