473,757 Members | 10,754 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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::connec t(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("CO M1:");
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 2620

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 misunderstandin g 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 misunderstandin g you?
It seems you're misunderstandin g 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::connec t(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::connec t(int port) : input("COM1:"), inputthread(&in put.read)
{

}

This way the constructor of the member objects is called.

--
Thomas
Jul 19 '06 #5
In message <11************ **********@h48g 2000cwc.googleg roups.com>,
Calle Pettersson <CP*******@gmai l.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 misunderstandin g you?
You're misunderstandin g 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::connec t(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::connec t(int port) : input("COM1:"), inputthread(&in put.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_p tr 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_p tr<boost::threa dinputthread;
};

void COMConn::connec t( int port )
{
input.open( "COM1:");
inputthread.res et( 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(strin g) % sizeof(Aligned) ) ];
/* Suff happens... */

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

--

Frederick Gotham
Jul 19 '06 #10

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

Similar topics

4
1758
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
11115
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 iMyInt = 0;
13
27155
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
3854
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: how can I imagine where the compiler puts the code to initialize the variables? Is it done somehow this way that the compiler puts the values of the variables once into memory right as it does with the commands? c. Are boolean variables exceptions...
31
2240
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
5879
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 the worst idea since W's last one. Or I can do: int a = {1,2,3,4,5}; int *x=a;
12
2291
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
1844
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
4378
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
9489
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
9298
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
9906
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 captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9885
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9737
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8737
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
7286
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
5329
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
3399
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.