Alex44
Alex44

Reputation: 3855

class object array inside struct

I need to put an array of class objects inside a struct.

The class inside a header file:

class aClass
{
private:
   int num;
public:
   aClass();
   ~aClass();
   int getNum();
   void setNum(int num);
}

The typedef inside a another header file

#include "aClass.hpp"

typedef struct
{
   aClass* classObject[3];
} newType_t;

At least the application

newType_t l_obj;
l_obj.classObject[1]->getNum();

The compiler works but at execution it comes to an segmentation fault. How to define the type correctly?

Thanks a lot Alex


2nd try:

aClass.hpp

class aClass
{
private:
   int num;
public:
   aClass();
   ~aClass();
   int getNum();
   void setNum(int num);
};

app.hpp

class aClass;

typedef struct
{
   aClass classObject[3];
} newType_t;

app.cpp

newType_t l_obj;
l_obj.classObject[1].getNum();

g++

error: field 'classObject' has incomplete type

another try:

aClass.hpp

class aClass
{
private:
   int num;
public:
   aClass();
   ~aClass();
   int getNum();
   void setNum(int num);
};

app.hpp

#include "aClass.hpp"
typedef struct
{
   aClass classObject[3];
} newType_t;

app.cpp

newType_t l_obj;
l_obj.classObject[1].getNum();

g++

error: 'aClass' does not name a type

Upvotes: 1

Views: 1008

Answers (3)

Sam Varshavchik
Sam Varshavchik

Reputation: 118330

newType_t l_obj;

This declares an instance of the newType_t class, which contains three pointers to instances of the aClass class.

The pointers are not initialized to point to any valid, instantiated object.

l_obj.classObject[1]->getNum();

This dereferences the 2nd pointer in the array. Since this pointer is not initialized to a valid, instantiated object. In your case, this results in a segmentation fault.

Upvotes: 1

Emil Laine
Emil Laine

Reputation: 42828

You haven't initialized your pointers, so accessing them with _obj.classObject[1]-> causes undefined behavior (like a segmentation fault).

Upvotes: 2

David G
David G

Reputation: 96810

You have an array of pointers, which are uninitialized since you haven't told them where to point to. Using uninitialized pointers causes undefined behavior, which has manifested itself as a crash in your case.

You should have an array of objects since there is no use for pointers here:

aClass classObject[3];

Notice the removal of the * in the declaration. You can call the method by doing:

l_obj.classObject[1].getNum();

Also, typedef struct is unnecessary. You can name your structure directly:

struct newType_t { .. }

Upvotes: 5

Related Questions