Click here to Skip to main content
15,903,388 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
If so, wouldn't that cause any problem?

I guess if it is at all possible, the constructor should set the vector to null; otherwise it will create an infinite loop?

I think it is possible, but I am not sure. Sorry, the question may sound dumb.
Posted

1 solution

It is absolutely possible, but "infinite loop" is also possible, under the condition of the sufficient idiocy of the implementation :-). If you do it in the simplest possible way, it will immediately work, by a very simple reason: at the moment of construction, the vector contains zero elements:
C++
class VectorOfElementsWithVector {
public:
    void Add(VectorOfElementsWithVector &element) { m_vector.push_back(element); }
private:
    std::vector<VectorOfElementsWithVector> m_vector;
};

//... 

// no problem to add elements to the vector:
VectorOfElementsWithVector container, element;
container.Add(element);


Moreover, you could do the same with an array, but then you will need to use the heap. Only if you try to construct the instance of a similar class attempting to make sure that each vector has at least one element right in the constructor, it will cause infinite recursion.

—SA
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900