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];
}
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.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.