473,765 Members | 2,024 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 3372
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
1349
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
12227
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
2982
by: jimmij | last post by:
Hi, Please look at the code bellow /*******************/ class ctab { private: static const unsigned n=48;
17
2622
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
2623
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 the session-file, but the unserialization of the object simply won't work.
16
4193
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
2340
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 example: int g_var = 3; int main() {}
4
7385
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
9568
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 usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9399
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 synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10163
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. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8832
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7379
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 instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6649
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5423
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3532
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2806
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 effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.