-
June 15th, 2009, 12:16 PM
#1
How do I call a member's constructor when declaring a structure?
I created a structure, and its members are objects that require a constructor with an argument to be called to work. How do I call the objects' constructors when I declare an instance of the structure?
This is the structure:
Code:
struct full_set
{
key n,e,d;//n, e, and d are instances of the key class.
};
This is the key class:
Code:
class key
{
public:
key(int);//key.length is set to the value passed to the constructor.
//Other member functions
private:
int *keyset;//keyset is a dynamic array
bool *defined_keys;//defined_keys is a dynamic array
int length;//length is the length of the dynamic arrays
};
key::key(int set_length)
{//key.length is set to the value passed to the constructor.
length = set_length;
//Also, create the dynamic arrays.
keyset = new int[length];
defined_keys = new bool[length];
//more code
}
Since the constructor in the key class creates the dynamic arrays, it needs to be called whenever an instance is created. When I create an instance of the full_set structure, how do I call the constructor for its members?
-
June 15th, 2009, 12:20 PM
#2
Re: How do I call a member's constructor when declaring a structure?
Use an initialization list in the constructor definition.
-
June 15th, 2009, 12:20 PM
#3
Re: How do I call a member's constructor when declaring a structure?
The way that I would do would be to provide a constructor:
Code:
struct full_set
{
full_set(const key& n, const key& e, const key& d) : n(n), e(e), d(d) {}
key n,e,d;
};
//
full_set x(key(1), key(2), key(3));
You could also use initialiser syntax, e.g.,
Code:
full_set x = {key(1), key(2), key(3)};
-
June 15th, 2009, 12:22 PM
#4
Re: How do I call a member's constructor when declaring a structure?
you might define a default constructor for the struct full_set that passes default values to your key objects:
Code:
struct full_set
{
full_set()
: n(0), e(0), d(0)
{}
key n,e,d;//n, e, and d are instances of the key class.
};
or you can define a constructor that takes parameters and uses them to construct your key objects:
Code:
struct full_set
{
full_set( int a, int b, int c)
: n(a), e(b), d(c)
{}
key n,e,d;//n, e, and d are instances of the key class.
};
or a combination of both...
-
June 15th, 2009, 12:31 PM
#5
Re: How do I call a member's constructor when declaring a structure?
Thanks, guys! I put a constructor in my structure like you suggested, and it worked.
Tags for this Thread
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|