OOD (Object Oriented Design) Question

Can member variables of a class be of the same type?

I've been trying to find the answer to this question and keep coming up short. I know in structs we can use variables of different types. However, I can't seem to find any information talking about the above statement in my book. Any ideas.
Can member variables of a class be of the same type?
Yes, no problem with that

[EDIT]Ok I misinterpreted the question. No you cannot have a variable that has the type of the encompassing class (reason as mentioned below)
Last edited on
This is not allowed.
1
2
3
4
5
6
7
8
9
10
11
12
class Node;
class Node
{
public:
    Node n;
};

int main(int argc, char* argv[])
{
    Node node;
    return 0;
}


But this is...
1
2
3
4
5
6
7
8
9
10
11
12
class Node;
class Node
{
public:
    static Node n;
};

int main(int argc, char* argv[])
{
    Node node;
    return 0;
}


and so is this...
1
2
3
4
5
6
7
8
9
10
11
12
class Node;
class Node
{
public:
    Node *n;
};

int main(int argc, char* argv[])
{
    Node node;
    return 0;
}
Last edited on
closed account (D80DSL3A)
If an instance of a class contains an instance of itself, then that instance contains an instance and so on ad infinitum so that a single instance would require infinite memory.

So it's not allowed.
Topic archived. No new replies allowed.