473,320 Members | 2,145 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

Initialize an array of classes?

Hi all,

I have a class that contains a member variable that is an array of class
instances:

class MyClass {
private:
SomeClass m_someClass;
SomeClass m_arrayOfClasses[2];
};

Now, the SomeClass class doesn't have a default (paramterless) constructor,
so I need to call its constructor in my initialization list of the MyClass
constructor, kind of like this:

// Constructor
MyClass::MyClass(void) :
// This compiles ok
m_someClass( constructor_arguments ),

// This doesn't compile
m_arrayOfClasses[0]( constructor_arguments ),
m_arrayOfClasses[1]( constructor_arguments )
{}

How do I initialize the array of class instances?

TIA - Bob
Jul 30 '08 #1
11 2290
Here is a complete C++ console app example that demonstrates what I'm trying
to do. The challenge is to change InnerValue to an array and figure out how
to call the constructor for each element of the array.

TIA - Bob

#include "stdafx.h"
#include <iostream>
using namespace std;

class CInner {
public:
// Constructor
CInner(int x) : Value(x) {}

// Member variable
int Value;
};

class COuter {
public:
CInner InnerValue;

// Constructor
COuter() :
InnerValue(2)
{}
};

int _tmain(int argc, _TCHAR* argv[])
{
COuter x;
cout << x.InnerValue.Value << endl;
return 0;
}
Jul 30 '08 #2
Well, I found a way to get kind of what I'm after. Instead of trying to
have an array of class instances, I can create an array of pointers to class
instances. That way I can use the "new" operator in the body of the
constructor to initialize the array. Of course, this means that I need to
go through my code and change all of the relevant "." operators to "->"
operators, but that's easily enough done in this case.

But I'm still curious as to whether or not it's possible to initialize an
array of classes if the class doesn't have a default constructor.
Jul 30 '08 #3
Bob Altman wrote:
Hi all,

I have a class that contains a member variable that is an array of class
instances:

class MyClass {
private:
SomeClass m_someClass;
SomeClass m_arrayOfClasses[2];
};

Now, the SomeClass class doesn't have a default (paramterless) constructor,
so I need to call its constructor in my initialization list of the MyClass
constructor, kind of like this:

// Constructor
MyClass::MyClass(void) :
// This compiles ok
m_someClass( constructor_arguments ),

// This doesn't compile
m_arrayOfClasses[0]( constructor_arguments ),
m_arrayOfClasses[1]( constructor_arguments )
{}

How do I initialize the array of class instances?
Bob:

If SomeClass is copyable you can do

MyClass::MyClass():
m_someClass( constructor_arguments )
{
m_arrayOfClasses[0] = SomeClass( constructor_arguments0 );
m_arrayOfClasses[1] = SomeClass( constructor_arguments1 );
}

--
David Wilkinson
Visual C++ MVP
Jul 30 '08 #4
Bob Altman wrote:
Well, I found a way to get kind of what I'm after. Instead of
trying to have an array of class instances, I can create an array
of pointers to class instances. That way I can use the "new"
operator in the body of the constructor to initialize the array. Of
course, this means that I need to go through my code and change
all of the relevant "." operators to "->" operators, but that's
easily enough done in this case.
But I'm still curious as to whether or not it's possible to
initialize an array of classes if the class doesn't have a default
constructor.
No, there is no way of initializing member array in the current
language.

In the upcoming revision, C++09, there is a generalized "initializer
list" feature that will possibly help in cases like this.
Bo Persson
Jul 30 '08 #5
Hi Bob,
Currently you cannot use member initialization list for a nonstatic array of a class if it does not have a default constructor. When you try to initialize the array, you will encounter the compiler
error C2536. You may refer to:
Compiler Error C2536
http://msdn.microsoft.com/en-us/library/9f53ks1w.aspx

If the class has a default constructor, you can explicitly initialize it like the following code:
class CInner {
public:
// Constructor
CInner(int x) : Value(x) {}
CInner(){}

// Member variable
int Value;
};

class COuter {
public:
CInner InnerValue;
CInner m_Inners[2];

// Constructor
COuter() :
InnerValue(2),m_Inners()
{}
};

The code can be compiled, however you may encounter the warning C4351 and I do not think that it is useful to use such initialization for an array.
You can refer to this article for further inforamtion:
Compiler Warning (level 1) C4351
http://msdn.microsoft.com/en-us/library/1ywe7hcy.aspx

Best regards,
Charles Wang
Microsoft Online Community Support
================================================== =========
Delighting our customers is our #1 priority. We welcome your
comments and suggestions about how we can improve the
support we provide to you. Please feel free to let my manager
know what you think of the level of service provided. You can
send feedback directly to my manager at: ms****@microsoft.com.
================================================== =========
Get notification to my posts through email? Please refer to
http://msdn.microsoft.com/subscripti...#notifications.

Note: The MSDN Managed Newsgroup support offering is for
non-urgent issues where an initial response from the community
or a Microsoft Support Engineer within 1 business day is acceptable.
Please note that each follow up response may take approximately
2 business days as the support professional working with you may
need further investigation to reach the most efficient resolution.
The offering is not appropriate for situations
that require urgent, real-time or phone-based interactions or complex
project analysis and dump analysis issues. Issues of this nature are best
handled working with a dedicated Microsoft Support Engineer by
contacting Microsoft Customer Support Services (CSS) at
http://msdn.microsoft.com/subscripti...t/default.aspx.
================================================== ==========
This posting is provided "AS IS" with no warranties, and confers no rights.
================================================== =======
Jul 31 '08 #6
David Wilkinson wrote:
Bob Altman wrote:
>Hi all,

I have a class that contains a member variable that is an array of
class instances:

class MyClass {
private:
SomeClass m_someClass;
SomeClass m_arrayOfClasses[2];
};

Now, the SomeClass class doesn't have a default (paramterless)
constructor, so I need to call its constructor in my initialization
list of the MyClass constructor, kind of like this:

// Constructor
MyClass::MyClass(void) :
// This compiles ok
m_someClass( constructor_arguments ),

// This doesn't compile
m_arrayOfClasses[0]( constructor_arguments ),
m_arrayOfClasses[1]( constructor_arguments )
{}

How do I initialize the array of class instances?

Bob:

If SomeClass is copyable you can do

MyClass::MyClass():
m_someClass( constructor_arguments )
{
m_arrayOfClasses[0] = SomeClass( constructor_arguments0 );
m_arrayOfClasses[1] = SomeClass( constructor_arguments1 );
}
Don't think so... all members have to be fully constructed before the body
of the user-defined constructor begins to execute. With no parameter-less
constructor, and no way to pass parameters to the array element
constructors, it's not possible.

OTOH, you should be able to make a fixed-length std::vector alike that does
this, using an embedded char array, sizeof, and placement new. Be careful
about destroying the right set of already-fully-constructed elements if any
of the element constructors throw, be careful to destroy the elements in the
array's destructor, and block copy construction and assignment operators,
and you should be golden. This will, of course, be a lot more general in
C++0x with variadic templates and closures, but C++03 is perfectly capable
of making a type-specific initializable array class.
Jul 31 '08 #7
Ben Voigt [C++ MVP] wrote:
David Wilkinson wrote:
>Bob Altman wrote:
>>Hi all,

I have a class that contains a member variable that is an array of
class instances:

class MyClass {
private:
SomeClass m_someClass;
SomeClass m_arrayOfClasses[2];
};

Now, the SomeClass class doesn't have a default (paramterless)
constructor, so I need to call its constructor in my initialization
list of the MyClass constructor, kind of like this:

// Constructor
MyClass::MyClass(void) :
// This compiles ok
m_someClass( constructor_arguments ),

// This doesn't compile
m_arrayOfClasses[0]( constructor_arguments ),
m_arrayOfClasses[1]( constructor_arguments )
{}

How do I initialize the array of class instances?
Bob:

If SomeClass is copyable you can do

MyClass::MyClass():
m_someClass( constructor_arguments )
{
m_arrayOfClasses[0] = SomeClass( constructor_arguments0 );
m_arrayOfClasses[1] = SomeClass( constructor_arguments1 );
}

Don't think so... all members have to be fully constructed before the body
of the user-defined constructor begins to execute. With no parameter-less
constructor, and no way to pass parameters to the array element
constructors, it's not possible.

OTOH, you should be able to make a fixed-length std::vector alike that does
this, using an embedded char array, sizeof, and placement new. Be careful
about destroying the right set of already-fully-constructed elements if any
of the element constructors throw, be careful to destroy the elements in the
array's destructor, and block copy construction and assignment operators,
and you should be golden. This will, of course, be a lot more general in
C++0x with variadic templates and closures, but C++03 is perfectly capable
of making a type-specific initializable array class.
Ben:

Mmmm, I guess you're right. Oh well.

Of course, this could be fixed by creating a default constructor for SomeClass...

--
David Wilkinson
Visual C++ MVP
Jul 31 '08 #8
Bob - I am trying to do something very similar by having an array of a class
inside the other class but have the array created dynamically through the
main class constructor.

can I see your code on how you did this with the pointers?
"Bob Altman" wrote:
Well, I found a way to get kind of what I'm after. Instead of trying to
have an array of class instances, I can create an array of pointers to class
instances. That way I can use the "new" operator in the body of the
constructor to initialize the array. Of course, this means that I need to
go through my code and change all of the relevant "." operators to "->"
operators, but that's easily enough done in this case.

But I'm still curious as to whether or not it's possible to initialize an
array of classes if the class doesn't have a default constructor.
Aug 5 '08 #9
Paul Pavlicko wrote:
Bob - I am trying to do something very similar by having an array of
a class inside the other class but have the array created dynamically
through the main class constructor.

can I see your code on how you did this with the pointers?
Just use std::vector<Tfor this, if a native class, or clr::array<Tif a
ref class.
>

"Bob Altman" wrote:
>Well, I found a way to get kind of what I'm after. Instead of
trying to have an array of class instances, I can create an array of
pointers to class instances. That way I can use the "new" operator
in the body of the constructor to initialize the array. Of course,
this means that I need to go through my code and change all of the
relevant "." operators to "->" operators, but that's easily enough
done in this case.

But I'm still curious as to whether or not it's possible to
initialize an array of classes if the class doesn't have a default
constructor.

Aug 6 '08 #10
Thanks all. That answers my question.
Aug 8 '08 #11
Paul, I just hacked up my original post. No guarantees that I didn't mangle
something...

#include "stdafx.h"
#include <iostream>
using namespace std;

class CInner {
public:
// Constructor
CInner(int x) : Value(x) {}

// Member variable
int Value;
};

class COuter {
public:
CInner InnerValue[5]; // Won't compile
CInner* InnerValue[5] // Array of pointers

// Constructor
COuter() :
// InnerValue(2) // Remove initializer
{
// Initialize the array in the body of the constructor
for (int i = 0; i < 5; i++) {
InnerValue[i] = new CInner(i);
}
}
};

int _tmain(int argc, _TCHAR* argv[])
{
COuter x;
cout << x.InnerValue.Value << endl;
return 0;
}
Aug 8 '08 #12

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
by: SamMan | last post by:
Is there an easy way to re-initialize an array, other than looping through it's length and setting the values to null, or ""? Would unset() be a wise choice? Thanks again -- SamMan
6
by: steveneng | last post by:
C++ Primer Plus Programming Exercises 4th Ed - Prate Help I'm trying to refresh myself and I'm stuck on this problem (not homework/school related but for personal advancement). 6: Do...
4
by: Mark Hannon | last post by:
I am trying to initialize an array only once so it can be seen & used by any functions that need it. As I understand it, if a variable is declared by itself outside of any functions, its scope is...
2
by: slack_justyb | last post by:
Hello, I'm trying to figure the best way of doing the following. *I need an array of strings that are globally accessable from within 'arrayhere.h' *I need that array of strings to not change...
6
by: Ramprasad A Padmanabhan | last post by:
I have a simple structure defined like this struct userid { char uid; int insize; int outsize; }; typedef struct userid user;
2
by: deko | last post by:
I trying to create a jagged array of two arrays, with the second array being an array of two-dimensional arrays. A graphical representation might look like this: x y y y x y x y y x ...
18
by: toton | last post by:
Hi, In C++ when I initialize an array it, also initializes the class that it contains, which calls the default constructor. However, I want to initialize the array only (i.e reserve the space) and...
15
by: thinktwice | last post by:
char a = { 0 } is it ok?
38
by: Zytan | last post by:
What is the difference between these two lines? Dim args As Object() = New Object() {strText} Dim args As Object() = {strText} args seems usuable from either, say, like so: ...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
0
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.