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];

Recommended Answers

All 2 Replies

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.

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;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.