0

If I have a class, MyClass, can I declare an array of MyClass on the heap, within the constructor of MyClass?

I can do this in C# but it doesnt seem to like it in C++?

I also get an error about no appropriate constructor for type MyClass??

class MyClass
{
    public:
        MyClass(int);
    private
        MyClass* array;
};


MyClass::MyClass(int size){
    array = new MyClass[size];
}
1
  • You'd run out of memory, yes? Because the constructors chain together, just eating up more and more of (heap or stack, doesn't matter). Commented May 26, 2012 at 23:41

2 Answers 2

4

In order to have an array of something, said something has to be default-constructible. Your MyClass isn't since it needs an int to be constructed.

What C# does is comparable to:

MyClass** array = new MyClass*[size];

Where pointers are default constructible, so its allowed. Basically, whenever you do SomeObject in C# its the equivalent of SomeObject* in C++. Except that the code would be horribly inefficient, even worse than its C# counterpart, and there would be leaks everywhere.

Sign up to request clarification or add additional context in comments.

15 Comments

Is that line of code what I could use to fix it? Would there be any special way which I have to use the array afterwards?
@Jon: No, that's not how you fix it, that's how you work around it. Is there a reason for MyClass not to be default-constructible?
I just want to store an collection of MyClass objects where I can traverse through. In C# I wouldnt use Lists, I would just create an array of MyClass[]
This also means the constructor of the class isn't called within itself, which would lead to problems.
@tmpearce: I failed to notice that! You should place a proper answer, I'd +1 it.
|
3

You have a more fundamental problem with your approach here than how to construct an array.

Think about it this way:

class A
{
   A* a;
public:
   A();
};
A::A()
{
   a = new A();
}

What happens? You try and create an A; within the constructor, a new A is created. Within that constructor, another new A is created...

Boom, out of memory.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.