Skip to main content
GameDev.net gamedev.net
🔒 Locked

Struct Initialization Within Struct

Started by pixelartist Jun 17, 2012 at 7:11 PM 1 replies 1.7k views
Original Post
pixelartist
pixelartist
C++

Is it possible to call a constructor with parameters for a struct within another struct? (Something like this, though VC++ is highlighting the "2" in myA and saying it wants a type specifier, so this is obviously wrong).

[source lang="cpp"]struct A{
int iSize;
A(int x = 10) { iSize = x; }
}; // A

struct B{
A myA(2);
}; // B[/source]

Essentially I want a struct that has a standardized initial Size member, but I also want to be able to specify a different Size member for it when it is itself a member of other structs.
clb
clb
Yes, but unfortunately C++ doesn't allow you to conveniently do the initialization like you do on line 7. You'll have to do it in a constructor, like as follows:

[source lang="cpp"]struct A{
int iSize;
A(int x = 10) { iSize = x; }
}; // A

struct B{
A myA;

B()
:myA(2)
{
}
}; // B[/source]

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.