0

I looked around and I didn't quite find what I was looking for.

I know that to initialize an array of objects, we have to go something like this :

Object *array[10];

But my question is : Why exactly can't we just go like this..

Object array[10];

3
Contributors
2
Replies
3
Views
7 Years
Discussion Span
Last Post by necrolin
0

Object array_[10];
is an array of Object and all off the Objects are constructed with default constructor. But the code that below
Object * array_[10];
is an array of Object pointer. The array_ array holds just pointers and the pointers point the Object class's object and non of them was constructed unless you initialize all of them by new operator.

0

Who says you can't because my C++ book says you can and my test program works fine too.

#include <iostream>
#include <cstdlib>

using namespace std;

class MyObject
{
	string data;
public:
	MyObject(string a) : data(a) {}
	void print() const { cout << data; };
};

int main()
{
	MyObject mo[4] = { MyObject("This "), MyObject("works "), MyObject("just "), MyObject("fine.")};
	
	for (int i = 0; i < 4; i++)
	{
		mo[i].print();
	}
	
	return EXIT_SUCCESS;
}
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.