Dynamic Arrays inside Classes

Hello,

I'm trying to write a class that contains data and a dynamic array of the same class type.

Is that possible?And how can I write that?
LVL 1
SerphAsked:
Who is Participating?

[Webinar] Streamline your web hosting managementRegister Today

x
 
Infinity08Connect With a Mentor Commented:
class Test {
  Test *dyn_arr;
};
0
 
KurtVonCommented:
I'll even go one further and say this works fine:

#include <vector>
   
class DynArrayTest{
public:
    DynArrayTest();
    ~DynArrayTest();
   
    std::vector<DynArrayTest> testArray;
};
0
 
Infinity08Commented:
That's basically the same, KurtVon. As long as you don't include an instance of the class in the class itself, it's fine. So, this will NOT work :

class Test {
  Test dyn_arr;
};

for obvious reasons (you'd have an infinite inclusion, and an infinite size of the Test class).

The example KurtVon gave also works, because the elements of the vector are not stored in the class body, but rather a "reference" to the elements.
0
The new generation of project management tools

With monday.com’s project management tool, you can see what everyone on your team is working in a single glance. Its intuitive dashboards are customizable, so you can create systems that work for you.

 
Infinity08Commented:
May I ask why you gave a B grade ? Is something still unclear ? If so, you can always ask for clarification ... You don't need to accept a reply that doesn't fully answer your question !
0
 
SerphAuthor Commented:
I thought I gave it an A?! Must have pressed enter when I selected A?
How can I correct this? *Sorry!*
0
 
Infinity08Commented:
There's no problem. I just wanted to make sure that you didn't select the reply without understanding it.

Requests for modifications can be done by posting a 0-point question in the Community support area. But as I said, there's no need, as long as I know that the reply was clear to you :)
0
All Courses

From novice to tech pro — start learning today.