Question:
New at C++ programming and need a bit of guidance...?
anonymous
2015-05-20 11:47:03 UTC
If I have two classes, let's say

class Pink
and
class Yellow

and I want to create an array as a data member in class Yellow that point to class pink. What will my data remember of array format look like.

class Yellow
{
int size = 20;
Pink array[size];
int *pointTo = &Pink;

--------
}

Putting everything together is a bit confusing.
Three answers:
husoski
2015-05-20 13:16:15 UTC
C++ does not allow variable-length arrays. Array dimensions must be known at compile time. To make that array declaration work, size must be made both const and static.



class Yellow

{

static const int size = 20;

Pink array[size];

.... more stuff.

};



That is the only context that allows initialization inside of a class definition...a const static of some sort of integral type (long, unsigned , char, int, etc.) Nothing else. So your pointer initialization wouldn't work, even if you fixed it. But, for the record:



int *point_to = &Pink;



...fails because Pink isn't a variable (it's a type, and you can't take the address of a type). Even if you fix that to:



int *point_to = &array;



... you get an error because & array is a pointer to an array of Pink objects, not to an int. You need to fix that to:



Pink *point_to = array; // no & needed since an array



That will work when declaring a local variable, but not a class or struct member.



In C++, non-static member variables ("fields") are initialized by a constructor. Period. Best practice is to use the member initialization list the constructor header. Here's a sample that compiles, so you can look at the parts. The Pink class definition is just a stub so that the Yellow class will compile.



// Pink class definition:



class Pink

{

int value;

public:

Pink(int val=0);

int getvalue();

};



// Pink class implementation:



Pink::Pink(int val) : value(val) {}



int Pink::getvalue()

{

return value;

}



// Yellow class definition:



class Yellow

{

const static int size = 20;

Pink array[size];

Pink *pointTo;

public:

Yellow();

Pink &getpink(int index);

Pink *getpoint();

};



// Yellow class implementation:



Yellow::Yellow() : pointTo(array)

{

}



Pink &Yellow::getpink(int index)

{

return array[index];

}



Pink *Yellow::getpoint()

{

return pointTo;

}
anonymous
2015-05-20 12:13:50 UTC
Thank you Rob! I'm trying to make it as an array, not a vector...
Rob
2015-05-20 11:59:02 UTC
http://pastebin.com/jSXZmxLD


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...