473,549 Members | 2,701 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Initializing composed objects

If I have this situation

class X
{
Z z;
Y y;
};

Class X has two objects of type Z and Y. How do I initialize z and y
with non default constructors?

X::X()
{
z(1);
y(2);
}

If I do something like the previous I get the following error:

line 2, Error: Could not find Z::Z() to initialize z.
line 2, Error: Could not find Y::Y() to initialize y.
line 3, Error: Only a function may be called.
line 3, Error: Only a function may be called.

Oct 20 '06 #1
6 3356
al******@gmail. com wrote:
If I have this situation

class X
{
Z z;
Y y;
};

Class X has two objects of type Z and Y. How do I initialize z and y
with non default constructors?
Use the constructor _initializer_li st_ (look it up).
>
X::X()
{
z(1);
y(2);
}

If I do something like the previous I get the following error:

line 2, Error: Could not find Z::Z() to initialize z.
line 2, Error: Could not find Y::Y() to initialize y.
line 3, Error: Only a function may be called.
line 3, Error: Only a function may be called.
V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Oct 20 '06 #2

al******@gmail. com wrote:
If I have this situation

class X
{
Z z;
Y y;
};

Class X has two objects of type Z and Y. How do I initialize z and y
with non default constructors?

X::X()
{
z(1);
y(2);
}
The exact same way you would initialize Z if it had a member.

class Z
{
int z;
public:
Z() : z(0) { } // def ctor
Z(int n) : z(n) { } // parametized ctor
};

int main()
{
Z instance_0; // instance_0.z == 0
Z instance_1(1); // instance_1.z == 1
}

Oct 20 '06 #3

Salt_Peter wrote:
al******@gmail. com wrote:
If I have this situation

class X
{
Z z;
Y y;
};

Class X has two objects of type Z and Y. How do I initialize z and y
with non default constructors?

X::X()
{
z(1);
y(2);
}

The exact same way you would initialize Z if it had a member.

class Z
{
int z;
public:
Z() : z(0) { } // def ctor
Z(int n) : z(n) { } // parametized ctor
};

int main()
{
Z instance_0; // instance_0.z == 0
Z instance_1(1); // instance_1.z == 1
}
The goal of what I am trying to do is to give some variables of type Z
and Y scope of class X but delay there initalization until all other
dependencies have been met. For example the Constructor of X may have
to go to the database before it can populate Z and Y with thier values.
So in that case I don't think constructor initalizer list technique
would be able to be used in that case.

Oct 20 '06 #4
al******@gmail. com wrote:
Salt_Peter wrote:
>al******@gmail. com wrote:
>>If I have this situation

class X
{
Z z;
Y y;
};

Class X has two objects of type Z and Y. How do I initialize z and y
with non default constructors?

X::X()
{
z(1);
y(2);
}
[...]

The goal of what I am trying to do is to give some variables of type Z
and Y scope of class X but delay there initalization until all other
dependencies have been met. For example the Constructor of X may have
to go to the database before it can populate Z and Y with thier
values. So in that case I don't think constructor initalizer list
technique would be able to be used in that case.
You cannot *initialise* them that way. You can only hope to *assign*
them at best, if you have to do

X::X()
{
/* some complicated processing */
z = Z(somevalue_fro m_processing);
y = Y(someothervalu e);
}

Now, since your 'Z' and 'Y' don't seem to have default constructors,
you _have_ to provide some values to *initialise* the members with.
So, it gets ugly relatively quickly:

X::X() : z(dummy_value_f or_z), y(dummy_value_f or_y)
{
/* some complicated processing */
z = Z(somevalue_fro m_processing);
y = Y(someothervalu e);
}

Perhaps you can re-design your initialisation procedure...

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Oct 20 '06 #5

alacr...@gmail. com wrote:
Salt_Peter wrote:
al******@gmail. com wrote:
If I have this situation
>
class X
{
Z z;
Y y;
};
>
Class X has two objects of type Z and Y. How do I initialize z and y
with non default constructors?
>
X::X()
{
z(1);
y(2);
}
The exact same way you would initialize Z if it had a member.

class Z
{
int z;
public:
Z() : z(0) { } // def ctor
Z(int n) : z(n) { } // parametized ctor
};

int main()
{
Z instance_0; // instance_0.z == 0
Z instance_1(1); // instance_1.z == 1
}

The goal of what I am trying to do is to give some variables of type Z
and Y scope of class X but delay there initalization until all other
dependencies have been met. For example the Constructor of X may have
to go to the database before it can populate Z and Y with thier values.
So in that case I don't think constructor initalizer list technique
would be able to be used in that case.
And why not? Whats preventing from initializing a variable to a valid
state and then reset the variable with a some dependancy when
available? Likewise, whats preventing you from completing some
dependancy and still intialize the variables in that init list?

Remember job #1, always , always initialize all your members. Even if
you will never use them. Take as an example a pointer. If you set that
pointer to 0 in the init list and happen to use it without
initialization it by accident - the result and the solution will be
obvious. If that pointer isn't initialized at all, you'll dig high and
low for the bug for a week. The same applies for any member.

Why take away the support a compiler can give you?
Interestingly enough, take a look at what happens if you do have a
dependancy:

#include <iostream>

class Z
{
char m_char;
public:
Z() : m_char( getInput() ) { std::cout << "Z()\n"; } // def ctor
~Z() { std::cout << "~Z()\n"; }
/* member functions */
char getInput() const
{
std::cout << "enter a char between b and e (default: a): ";
char c;
std::cin >c;
if( (c >= 'b' && c <= 'e' ) && std::cin.good() )
{
return c;
} else {
return 'a';
}
}
const char& get() const { return m_char; }
};

int main()
{
Z instance;
std::cout << "instance.m_cha r = ";
std::cout << instance.get() << std::endl;
return 0;
}

/* sample output
enter a character between b and e (default: a): c
Z()
instance.m_char = c
~Z()
*/

Try a primitive array of Zs.

Oct 20 '06 #6

Salt_Peter wrote:
alacr...@gmail. com wrote:
Salt_Peter wrote:
al******@gmail. com wrote:
If I have this situation

class X
{
Z z;
Y y;
};

Class X has two objects of type Z and Y. How do I initialize z and y
with non default constructors?

X::X()
{
z(1);
y(2);
}
>
The exact same way you would initialize Z if it had a member.
>
class Z
{
int z;
public:
Z() : z(0) { } // def ctor
Z(int n) : z(n) { } // parametized ctor
};
>
int main()
{
Z instance_0; // instance_0.z == 0
Z instance_1(1); // instance_1.z == 1
}
The goal of what I am trying to do is to give some variables of type Z
and Y scope of class X but delay there initalization until all other
dependencies have been met. For example the Constructor of X may have
to go to the database before it can populate Z and Y with thier values.
So in that case I don't think constructor initalizer list technique
would be able to be used in that case.

And why not? Whats preventing from initializing a variable to a valid
state and then reset the variable with a some dependancy when
available? Likewise, whats preventing you from completing some
dependancy and still intialize the variables in that init list?

Remember job #1, always , always initialize all your members. Even if
you will never use them. Take as an example a pointer. If you set that
pointer to 0 in the init list and happen to use it without
initialization it by accident - the result and the solution will be
obvious. If that pointer isn't initialized at all, you'll dig high and
low for the bug for a week. The same applies for any member.

Why take away the support a compiler can give you?
Interestingly enough, take a look at what happens if you do have a
dependancy:

#include <iostream>

class Z
{
char m_char;
public:
Z() : m_char( getInput() ) { std::cout << "Z()\n"; } // def ctor
~Z() { std::cout << "~Z()\n"; }
/* member functions */
char getInput() const
{
std::cout << "enter a char between b and e (default: a): ";
char c;
std::cin >c;
if( (c >= 'b' && c <= 'e' ) && std::cin.good() )
{
return c;
} else {
return 'a';
}
}
const char& get() const { return m_char; }
};

int main()
{
Z instance;
std::cout << "instance.m_cha r = ";
std::cout << instance.get() << std::endl;
return 0;
}

/* sample output
enter a character between b and e (default: a): c
Z()
instance.m_char = c
~Z()
*/

Try a primitive array of Zs.
Ok, After the last two responses I understand the situation much
better. So thank you Victor Bazarov and Salt_Peter for the help.

Oct 20 '06 #7

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

Similar topics

0
1337
by: Francesc Guim Bernat | last post by:
Dear collegues, I've this XML: <?xml version="1.0"?> <model> <entity id="1"> <object id="1"></object> <object id="2"></object> </entity>
1
417
by: Andreas Boehm | last post by:
Hi *.*, does the standard meanwhile define something about initializing variables by the compiler? I think, it is a side-effect of the OS used, if undefined global (static) variables are initialized to zero. What does the standard define for this? thanx Andreas
10
12186
by: Steve | last post by:
this code: private Array m_arrays = new Array; results in an array of 3 null Array objects. What am I missing?
12
2966
by: jimmij | last post by:
Hi, Please look at the code bellow /*******************/ class ctab { private: static const unsigned n=48;
17
2594
by: Calle Pettersson | last post by:
Coming from writing mostly in Java, I have trouble understanding how to declare a member without initializing it, and do that later... In Java, I would write something like public static void main(String args) { MyType aMember; ... aMember = new MyType(...) ... } However, in C++ this does not seem to work. I declare in class (it's
8
2615
by: carrion | last post by:
Hello everyone! I'm currently working on a MVC-framework and have run into an issue. I'm using separate script files to render the active page's CSS and Javascript Code. I want to pull the data from the page controller object, which is initialized in another script. I thought this wouldn't be a problem if I simply stored the controller in...
16
4153
by: Ray | last post by:
Hi all, After many years of C, I thought I'd move to C++ recently. I think because I think in C, I'm coming to a misunderstanding of something. I've created a class foo which contains a private variable which is a priority queue. In class foo's header file, I declared it as: class foo { private:
13
2315
by: WaterWalk | last post by:
Hello. When I consult the ISO C++ standard, I notice that in paragraph 3.6.2.1, the standard states: "Objects with static storage duration shall be zero-initialized before any other initialization takes place." Does this mean all non-local objects will be zero-initialized before they are initialized by their initializers(if they have)? For...
4
7362
by: Peskov Dmitry | last post by:
class simple_class { int data; public: simple_class() {data=10;}; simple_class(int val) : data(val){} }; int main() {
0
7520
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7450
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
7720
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
7957
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
5368
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
3500
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3481
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1941
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
0
763
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

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.