Creating a container class - Access violation

Hello there,

This being my first time on this forum, I hope my post is somewhat fitting to the rules and etiquette. I've only started learning C++ around two weeks ago so this might be a very basic question...

I'm trying to create a container class (ObjectArray) that holds an array of instances of another class (Object). I've boiled my problem down to the following code.

object.h
1
2
3
class Object
{
};


objectarray.h
1
2
3
4
5
6
7
8
9
10
#include "object.h"

class ObjectArray
{
private:
	int m_nLength;
	Object *m_pData;
public:
	void Initialise(int nLength);
};


objectarray.cpp
1
2
3
4
5
6
7
#include "objectarray.h"

void ObjectArray::Initialise(int nLength)
{
	m_pData = new Object[nLength];
	m_nLength = nLength;
}


main.cpp
1
2
3
4
5
6
7
8
#include "objectarray.h"

void main()
{
	ObjectArray *Objects;
	Objects = 0;
	Objects->Initialise(2);
}


The 2 in Objects->Initialise(2); is just an arbitrary number for testing purposes.

When I run this, I receive the following error:
Unhandled exception at 0x0041142e in Testing.exe: 0xC0000005: Access violation writing location 0x00000004.


Choosing Break brings me to line 5 in objectarray.cpp:
m_pData = new Object[nLength];

Mousing over m_pData gives me no tooltip (whereas nLength gives me '2' as expected).

I tried having a constructor for ObjectArray that set m_pData to 0, but that makes no difference. Inserting a new line into the Initialise function where m_pData is set to 0, produces the same error on that new line.

What is going wrong here? Thanks in advance!
Last edited on
The problem isn't with your ObjectArray class you just havent allocated any memory for Objects in main, it's a null pointer when you try to call Initialise on it
Last edited on
Aah, so the solution is adding the following to main.cpp:

Objects = new ObjectArray;

Not it's working... Though I need to get my head around using pointers a bit more!

Thank you, quirky.
Last edited on
Topic archived. No new replies allowed.