473,416 Members | 1,766 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,416 software developers and data experts.

Initializing without assigning

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
for serial port communication) like this:

#include <fstream>
#include <boost/thread/thread.hpp>

class COMConn {
public:
COMConn(int port);
~COMConn();

char *send(char);
char *send(char, char[]);
private:
void connect(int);

std::ifstream input;
std::ofstream output;

boost::thread inputthread;
boost::thread outputthread;
};

But when I want to initialize the threads and streams, I want to do
something like

void COMConn::connect(int port) {
this->input = std::ifstream("COM1:");
this->inputthread = boost::thread(&input.read); // Not correct, needs
arguments, but skip that for now
//etc for the others
}

How do you go about doing this in C++? I found that I could do
this->input.open("COM1:");
But that is hardly something that will work in general. I find this
very confusing I must say... Thanks you for any advice

Jul 19 '06 #1
17 2570

Calle Pettersson wrote:
Coming from writing mostly in Java, I have trouble understanding how to
declare a member without initializing it, and do that later...
General rule: don't. Just move the declaration to the point where you
initialize it, as any object is unusable until initialized.

You don't have to declare variables first; that's a old C habit which
is not
even needed in today's C, let alone in newer languages.

HTH
Michiel Salters

Jul 19 '06 #2

Mi*************@tomtom.com wrote:
Calle Pettersson wrote:
Coming from writing mostly in Java, I have trouble understanding how to
declare a member without initializing it, and do that later...

General rule: don't. Just move the declaration to the point where you
initialize it, as any object is unusable until initialized.

You don't have to declare variables first; that's a old C habit which
is not
even needed in today's C, let alone in newer languages.

HTH
Michiel Salters
Really? But if I need this to be accessible to the class, but can't
call the constructor in the class definition? (Need to know which com
port in this case)
Also, I didn't know that variables could be added to a class if they
aren't specified in the header?
Or am I misunderstanding you?

Jul 19 '06 #3
Calle Pettersson wrote:
Mi*************@tomtom.com wrote:
>Calle Pettersson wrote:
>>Coming from writing mostly in Java, I have trouble understanding
how to declare a member without initializing it, and do that
later...

General rule: don't. Just move the declaration to the point where you
initialize it, as any object is unusable until initialized.

You don't have to declare variables first; that's a old C habit which
is not
even needed in today's C, let alone in newer languages.

HTH
Michiel Salters
Really? But if I need this to be accessible to the class, but can't
call the constructor in the class definition? (Need to know which com
port in this case)
Also, I didn't know that variables could be added to a class if they
aren't specified in the header?
Or am I misunderstanding you?
It seems you're misunderstanding each other.

*Members* are declared first, in the class definition. Then, in the
initialiser list of a constructor, they are initialised. *Variables*
(non-member, stand-alone) don't need to be declared. Declare/define/
initialise them when needed.

class Class {
void *member; // a member: declaration
public:
Class() : member(0) {} // initialisation
};

int main() {
void *nonmember(0); // a variable: declaration/definition/init'n
}
V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Jul 19 '06 #4
Calle Pettersson schrieb:
#include <fstream>
#include <boost/thread/thread.hpp>

class COMConn {
public:
COMConn(int port);
~COMConn();

char *send(char);
char *send(char, char[]);
private:
void connect(int);

std::ifstream input;
std::ofstream output;

boost::thread inputthread;
boost::thread outputthread;
};

But when I want to initialize the threads and streams, I want to do
something like

void COMConn::connect(int port) {
this->input = std::ifstream("COM1:");
this->inputthread = boost::thread(&input.read); // Not correct, needs
arguments, but skip that for now
//etc for the others
}
Use initialization lists in the constructor if its possible:

void COMConn::connect(int port) : input("COM1:"), inputthread(&input.read)
{

}

This way the constructor of the member objects is called.

--
Thomas
Jul 19 '06 #5
In message <11**********************@h48g2000cwc.googlegroups .com>,
Calle Pettersson <CP*******@gmail.comwrites
>
Mi*************@tomtom.com wrote:
>Calle Pettersson wrote:
Coming from writing mostly in Java, I have trouble understanding how to
declare a member without initializing it, and do that later...

General rule: don't. Just move the declaration to the point where you
initialize it, as any object is unusable until initialized.

You don't have to declare variables first; that's a old C habit which
is not
even needed in today's C, let alone in newer languages.

HTH
Michiel Salters
Really? But if I need this to be accessible to the class, but can't
call the constructor in the class definition? (Need to know which com
port in this case)
Also, I didn't know that variables could be added to a class if they
aren't specified in the header?
Or am I misunderstanding you?
You're misunderstanding each other.

MS is saying that you don't need to declare local variables in a
function before you need them.

You're asking how to declare member variables of a class without
initialising them. The over-simplified answer is that you can't, because
the class's constructor must invoke _some_ constructor for each member.
If they need information that's not available at construction, you have
to pass it in by calling a "post-constructor" member function at some
later stage.

What you are probably overlooking is that C++, unlike Java, has value
semantics for class types. All the class members are actual value
objects, whereas the "members" of a Java class are really just disguised
pointers.

This means that the members of a C++ class "exist" in the sense that you
can pass around pointers or references to them as soon as they have been
constructed, and before any post-construction operations have taken
place.

--
Richard Herring
Jul 19 '06 #6
Thomas J. Gritzan wrote:
Calle Pettersson schrieb:
#include <fstream>
#include <boost/thread/thread.hpp>

class COMConn {
public:
COMConn(int port);
~COMConn();

char *send(char);
char *send(char, char[]);
private:
void connect(int);

std::ifstream input;
std::ofstream output;

boost::thread inputthread;
boost::thread outputthread;
};

But when I want to initialize the threads and streams, I want to do
something like

void COMConn::connect(int port) {
this->input = std::ifstream("COM1:");
this->inputthread = boost::thread(&input.read); // Not correct, needs
arguments, but skip that for now
//etc for the others
}

Use initialization lists in the constructor if its possible:

void COMConn::connect(int port) : input("COM1:"), inputthread(&input.read)
{

}

This way the constructor of the member objects is called.
As TJG says, you should initialize every member somehow in the
constructor. It looks from your example, however, that you want to
delay creation of several objects until the connect function is called.
To do this, make the members pointers (since you're already using
Boost, use boost::scoped_ptr to get automatic cleanup), initialize them
to 0 in the constructor (scoped_ptr will do this automatically, also),
and then create the objects on-the-fly in your member function:

class COMConn
{
public:
// ...

private:
void connect(int);
std::ifstream input;
boost::scoped_ptr<boost::threadinputthread;
};

void COMConn::connect( int port )
{
input.open( "COM1:");
inputthread.reset( new boost::thread( /*whatever*/ ) );
}

Cheers! --M

Jul 19 '06 #7
Calle Pettersson wrote:
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(...)
...
}
The roughly equivalent C++ code would be

MyType *aMember = 0;
....
aMember = new MyType(...);
Jul 19 '06 #8
Pete Becker wrote:
Calle Pettersson wrote:
>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(...)
...
}

The roughly equivalent C++ code would be

MyType *aMember = 0;
...
aMember = new MyType(...);
To the OP:

If 'aMember' is a local variable of the 'main' function ("method"), then
its name is wrong. It's not really a member, is it?

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Jul 19 '06 #9
Calle Pettersson posted:
Coming from writing mostly in Java, I have trouble understanding how to
declare a member without initializing it, and do that later...

If you want to use a pointer:

int main()
{
MyClass *p;

/* "p" contains garbage right now */
...
p = new MyClass; /* Object created here */
...

delete p; /* Object destroyed here */
}
Or perhaps if you wish to pre-allocate the memory:

#include <string>
#include <new>
using std::string;

union Aligned {
void *p;
long a;
long double b;
};
int main()
{
Aligned buf[
sizeof(string) / sizeof(Aligned)
+ !!(sizeof(string) % sizeof(Aligned)) ];
/* Suff happens... */

string &obj = *::new(&buf) string;
obj.~string();
}

--

Frederick Gotham
Jul 19 '06 #10
Frederick Gotham wrote:
Calle Pettersson posted:
>Coming from writing mostly in Java, I have trouble understanding how
to declare a member without initializing it, and do that later...


If you want to use a pointer:

int main()
{
MyClass *p;

/* "p" contains garbage right now */
...
p = new MyClass; /* Object created here */
There is simply *no sence* to declare 'p' before this statement.
That Calle has already been told. Just declare/define/initialise
it right where you first use it.
>

...

delete p; /* Object destroyed here */
}
Or perhaps if you wish to pre-allocate the memory:

#include <string>
#include <new>
using std::string;

union Aligned {
void *p;
long a;
long double b;
};
int main()
{
Aligned buf[
sizeof(string) / sizeof(Aligned)
+ !!(sizeof(string) % sizeof(Aligned)) ];
Could you elaborate what this all is for? What are you trying
to accomplish with all that?
>

/* Suff happens... */

string &obj = *::new(&buf) string;
obj.~string();
}
V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Jul 19 '06 #11
On Wed, 19 Jul 2006 12:11:14 -0400, "Victor Bazarov"
<v.********@comAcast.netwrote:
>Pete Becker wrote:
>Calle Pettersson wrote:
>>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(...)
...
}
The roughly equivalent C++ code would be

MyType *aMember = 0;
...
aMember = new MyType(...);

To the OP:

If 'aMember' is a local variable of the 'main' function ("method"), then
its name is wrong. It's not really a member, is it?
Moreover, uninitialized variables are nor allowed in Java.
Jul 19 '06 #12
Roland Pibinger wrote:
On Wed, 19 Jul 2006 12:11:14 -0400, "Victor Bazarov"
<v.********@comAcast.netwrote:
Pete Becker wrote:
Calle Pettersson wrote:
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(...)
...
}
The roughly equivalent C++ code would be

MyType *aMember = 0;
...
aMember = new MyType(...);
To the OP:

If 'aMember' is a local variable of the 'main' function ("method"), then
its name is wrong. It's not really a member, is it?
Correct, I came up with that method just to show my point, and did so
in an erronus way, which understandably caused some confusion... I'll
try to be more careful in reading my code before posting in the future.
Moreover, uninitialized variables are nor allowed in Java.
Yes they are, as long as you don't try to access them. This will work
just fine:
class MyClass {
public static void main(String[] args) {
MyObject obj;
// blahblahblah
obj = new MyObject();
// etc
}
}

Jul 19 '06 #13
Victor Bazarov posted:

> Aligned buf[
sizeof(string) / sizeof(Aligned)
+ !!(sizeof(string) % sizeof(Aligned)) ];

Could you elaborate what this all is for? What are you trying
to accomplish with all that?

You can't do the following, because the array might not be aligned properly
to accommodate a particular type:

char buffer[sizeof(T)];

::new(buffer) T;
A possible solution would be to use a union to ensure correct alignment.

(Have you not seen this "trick" before? It's quite common.)
--

Frederick Gotham
Jul 19 '06 #14
Frederick Gotham wrote:
Victor Bazarov posted:

>> Aligned buf[
sizeof(string) / sizeof(Aligned)
+ !!(sizeof(string) % sizeof(Aligned)) ];

Could you elaborate what this all is for? What are you trying
to accomplish with all that?


You can't do the following, because the array might not be aligned
properly to accommodate a particular type:

char buffer[sizeof(T)];

::new(buffer) T;
A possible solution would be to use a union to ensure correct
alignment.
And how using the union you used with a 'void*', a 'long', and
a 'long double' going to accomplish "correct alignment"?
(Have you not seen this "trick" before? It's quite common.)
No, I haven't. Not to say that I've seen all the code in the world,
of course. It does strike me as strange that instead of simply
declaring a local object of type 'std::string' you declare an array
of some weird union type and then use placement new to allocate
a string. And you're saying that it's *quite common*? Indeed...

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Jul 19 '06 #15
Victor Bazarov posted:
And how using the union you used with a 'void*', a 'long', and
a 'long double' going to accomplish "correct alignment"?

Pick the largest integer type.

Pick the largest floating point type.

Pick the largest pointer type.

Put them together and you've got some very strict alignment.

Is it guaranteed to be strict enough? I'm not sure.

Is it likely to be strict enough? Yes, very.

>(Have you not seen this "trick" before? It's quite common.)

No, I haven't. Not to say that I've seen all the code in the world,
of course. It does strike me as strange that instead of simply
declaring a local object of type 'std::string' you declare an array
of some weird union type and then use placement new to allocate
a string. And you're saying that it's *quite common*? Indeed...

Imagine you want to have a local object in a function, but you want some
other function to initialise it:

#include <new>

void OtherFunc(void * const);

int main()
{
char buffer[sizeof(MyType)];
/* Correct alignment not guaranteed */

OtherFunc(buffer);
}

void OtherFunc(void * const pbuf)
{
/* Do some stuff */

::new(pbuf) MyType();
}
--

Frederick Gotham
Jul 20 '06 #16
Frederick Gotham wrote:
Victor Bazarov posted:
>And how using the union you used with a 'void*', a 'long', and
a 'long double' going to accomplish "correct alignment"?


Pick the largest integer type.

Pick the largest floating point type.

Pick the largest pointer type.
What happens to the pointer-to-member type? Did you know their size
is not predetermined? And there is no way to tell which one is the
largest.
Put them together and you've got some very strict alignment.
Yes, but alignment is *always* implementation-defined. Shouldn't we
stop trying to fake implementation-defined behaviour with standard
methods?
Is it guaranteed to be strict enough? I'm not sure.
Exactly.
Is it likely to be strict enough? Yes, very.
Sorry, not good enough.
>>(Have you not seen this "trick" before? It's quite common.)

No, I haven't. Not to say that I've seen all the code in the world,
of course. It does strike me as strange that instead of simply
declaring a local object of type 'std::string' you declare an array
of some weird union type and then use placement new to allocate
a string. And you're saying that it's *quite common*? Indeed...


Imagine you want to have a local object in a function, but you want
some other function to initialise it:

#include <new>

void OtherFunc(void * const);

int main()
{
char buffer[sizeof(MyType)];
/* Correct alignment not guaranteed */

OtherFunc(buffer);
}

void OtherFunc(void * const pbuf)
{
/* Do some stuff */

::new(pbuf) MyType();
}
Don't see it as "common" either. What you ususally see done is

MyType myobject = OtherFunc();

It's not entirely "initialisation" but with optimizations the
compiler is allowed to do, it's *more likely* to be correct, and
therefore *more common*, AFAICT.

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Jul 20 '06 #17
Victor Bazarov posted:
>Is it likely to be strict enough? Yes, very.

Sorry, not good enough.

Presumably, that was the antecedent for the following:

http://groups.google.ie/group/comp.s...b27dc9f?hl=en&
--

Frederick Gotham
Jul 20 '06 #18

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

Similar topics

4
by: hrmadhu | last post by:
Hi, I wish to declare a vector of deque of int, which I do as follows. #include<vector> #include<deque> #include<iostream> using namespace std; int main(int argc, char* argv) {
2
by: ik | last post by:
Hello All, I am facing a problem as follows. I have a header file called myNameSpace.h which as the following contents. //Header file .. myNameSpace.h namespace myNameSpace { static int...
13
by: simondex | last post by:
Hi, Everyone! Does anyone know how to initialize an int array with a non-zero number? Thank You Very Much. Truly Yours, Simon Dexter
3
by: Felix Kater | last post by:
Some basic questions about variable initialization: a. Is it legal to initialize the variables i, b and l like this (see below) ? b. If so: At what time are they initialized? In other words:...
31
by: arun | last post by:
suppose i have a pointer to an array of integers.can i initialize each member of the array using pointers?plz explain
3
by: Bill Pursell | last post by:
I've found myself wanting to do this: int *x = {1,2,3,4,5}; Obviously, I can't do that. I can certainly non-portably hack it like int *x = (int *)"\x01\x00\x00\x00\x02\x00...", but that's...
12
by: Mik0b0 | last post by:
Hallo. Let's say, there is a structure struct struct10{ int a1; int a2; int a3; int a4; }count={ {10,20,30,40}, {50,60,70,80}
3
by: Reckoner | last post by:
would it be possible to use one of an object's methods without initializing the object? In other words, if I have: class Test: def __init__(self): print 'init' def foo(self): print 'foo'
6
by: Jai Prabhu | last post by:
Hi All, Consider the following piece of code: void func (void) { static unsigned char arr = "\x00\xAA\xBB"; fprintf (stderr, "0x%x\n", arr); fprintf (stderr, "0x%x\n", arr);
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
0
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,...
0
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...
0
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,...
0
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...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
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...
0
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...

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.