Class recursion

G

graf.laszlo

Hi,

Can I define a class A, wich has a private array member with base type
A?

class A {
private:
char* name;
A a[];
public:
A();
A(char* p_name);
~A();
}

Thank you,
László
 
N

Neelesh Bodas

Hi,

Can I define a class A, wich has a private array member with base type
A?

class A {
private:
char* name;
A a[];
public:
A();
A(char* p_name);
~A();
}

No.'a' can be array of pointers to A
A* a[];
Alternatively, 'a' can be static
static A a[]; // define outside the class.
 
G

graf.laszlo

Thank you.


Neelesh Bodas írta:
Hi,

Can I define a class A, wich has a private array member with base type
A?

class A {
private:
char* name;
A a[];
public:
A();
A(char* p_name);
~A();
}

No.'a' can be array of pointers to A
A* a[];
Alternatively, 'a' can be static
static A a[]; // define outside the class.
 
G

graf.laszlo

I redefined it as you indicated and I added a new constructor but I
need one more thing.
The class looks like this:

class A {
private:
char* name;
A* a[];
public:
A();
A(char* p_name);
A(char* p_name, A* p_a);
~A();
}

How should implement the constructors?
 
J

John Harrison

I redefined it as you indicated and I added a new constructor but I
need one more thing.
The class looks like this:

class A {
private:
char* name;
A* a[];
public:
A();
A(char* p_name);
A(char* p_name, A* p_a);
~A();
}

How should implement the constructors?

Surely that depends on what you want to do?

Part of the problem here is that you are using illegal syntax.

class A {
private:
char* name;
A* a[];

This is not legal C++. Your compiler might be accepting it but your
compiler is wrong. When you declare an array in C++ you have to say how
big it is. This is legal

class A {
private:
char* name;
A* a[10];

Now I'm guessing, but I would say that Neelesh Bodas misunderstood what
you want. I think that problably you want a dynamic array of A objects
inside your A class. That is perfectly legal, and you write it like this

class A {
private:
char* name;
A* a;

In the constructor you dynamically allocate however many A objects you
want. Like this

a = new A[n];

where n is the number of A objects you want.

John
 
M

Mateusz Loskot

[...]
How should implement the constructors?

Are you going to implement tree-like structure/collection with
recursively nested class?
If you are, then I think you should drop that approach and take a look
at Composite design pattern.
Cheesr
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,432
Messages
2,571,680
Members
48,796
Latest member
Greg L.

Latest Threads

Top