954,500 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Using constructor within a class array

I've built a class, one parent and multiple children, that I need to group together to eventually be stored in a single file. For the moment I've gone with something like this:

CObject *group //CObject is the class in question

group = (CObject*)calloc(1, sizeof(CObject)); //1 element just to start off


This compiles, and using "group[0]." calls the variables and methods from the class, which also compiles. But what I can't seem to access is the constructor. My class has both a blank default constructor and the standard initialized all variable constructor, the latter which I want to use. However, "group[0]." does not bring up the constructor option, and "group[0]()" does not compile. So how do I use my constructor?

RandV80
Newbie Poster
13 posts since Jul 2008
Reputation Points: 10
Solved Threads: 0
 

>But what I can't seem to access is the constructor.
This is where the C memory functions fall flat, they don't work well with constructors and destructors. I recommend ditching calloc and using new[]:

CObject *group = new CObject[N];

Or better yet, use the vector container class if you plan on resizing the collection:

#include <vector>

...

std::vector<CObject> group ( 1 ); // Start off with 1 element
Narue
Bad Cop
Administrator
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401
 

The calloc (and malloc) function never calls constructors; free() never calls destructor(s).
So using new and delete operators for class objects (or array of class objects) is not only recommendation or a good style symptom - it's one of the very strict C++ language specifications.

ArkM
Postaholic
2,001 posts since Jul 2008
Reputation Points: 1,234
Solved Threads: 348
 

Thanks, I'll give those a try. My OO coding is rusty and I forgot about these.

RandV80
Newbie Poster
13 posts since Jul 2008
Reputation Points: 10
Solved Threads: 0
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You