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?

Recommended Answers

All 3 Replies

>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

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.

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

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.