Sign in to follow this  
pixelartist

Struct Initialization Within Struct

Recommended Posts

pixelartist    622
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.

Share this post


Link to post
Share on other sites
clb    2147
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]

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this