473,320 Members | 1,802 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,320 software developers and data experts.

initializing a member pointer

hello, I have probably a stupid question, but I don't get one thing.
In the following source, the first constructor "does not work" - it
creates a pointer variable pI, sets ii as *pI, but this created pI is
not the member one, the *C::pI is still uninitialised. In the later
constructor it's ok.
What's wrong with the first one?
Thank you for your help and time

m
#include <iostream>

class C
{
private:
int *pI;
public:
/**/
// this constuctor does not work
C(int ii) {
int *pI = new int(ii);
}
/**/
// this one is ok
/*
C(int ii) {
int *pTmp = new int(ii);
pI = pTmp;
}
*/
~C() {delete pI;}
void print()
{
std::cout << " *pI = " << *pI << std::endl;
}
};
int main(int argc, char* argv[])
{
C d(3);
d.print();
}

Nov 28 '07 #1
4 1350
On Nov 28, 1:44 pm, maj...@majsta.net wrote:
hello, I have probably a stupid question, but I don't get one thing.
In the following source, the first constructor "does not work" - it
creates a pointer variable pI, sets ii as *pI, but this created pI is
not the member one, the *C::pI is still uninitialised. In the later
constructor it's ok.
What's wrong with the first one?
Thank you for your help and time

m

#include <iostream>

class C
{
private:
int *pI;
public:
/**/
// this constuctor does not work
C(int ii) {
int *pI = new int(ii);
}
/**/
// this one is ok
/*
C(int ii) {
int *pTmp = new int(ii);
pI = pTmp;
}
*/
~C() {delete pI;}
void print()
{
std::cout << " *pI = " << *pI << std::endl;
}};

int main(int argc, char* argv[])
{
C d(3);
d.print();
}
Hi,

In the first constructor by doing "int *pI = new int(ii);" you
effectively declare a local int* variable named pI and hide the class
member C::pI, at scope end pI is destroyed and C::pI becomes visible
again.

If you don't redeclare pI (which is a mistake in this case) you'll get
the right behaviour since the compiler will translate that to this-
>pI.
Cheers
Nov 28 '07 #2
On Nov 28, 2:44 pm, maj...@majsta.net wrote:
hello, I have probably a stupid question, but I don't get one thing.
In the following source, the first constructor "does not work" - it
creates a pointer variable pI, sets ii as *pI, but this created pI is
not the member one, the *C::pI is still uninitialised. In the later
constructor it's ok.
What's wrong with the first one?
Thank you for your help and time

m

#include <iostream>

class C
{
private:
int *pI;
public:
/**/
// this constuctor does not work
C(int ii) {
int *pI = new int(ii);
You defind a local pI, independent from C::pI. The pI is initialized
with an int with ii value. You don't intialize the C::pI. The scope of
pI is the constructor body. You should initialize pI like this:
C(int ii) : pI(new int(ii)) {}
}
/**/
// this one is ok
/*
C(int ii) {
int *pTmp = new int(ii);
pI = pTmp;
}
*/
~C() {delete pI;}
void print()
{
std::cout << " *pI = " << *pI << std::endl;
}};

int main(int argc, char* argv[])
{
C d(3);
d.print();
}
Nov 28 '07 #3
On Wed, 28 Nov 2007 03:44:32 -0800 (PST) in comp.lang.c++,
ma****@majsta.net wrote,
> // this constuctor does not work
C(int ii) {
int *pI = new int(ii);
}
As others have written, it is completely wrong to declare a local
variable here that is named the same as your member variable.

But it's still wrong to use assignment instead of construction to
build member variables. Not that there is much difference in the
case of ints, but what you have should still be written as:

C(int ii) : pI(new int(ii)) {
}

Then next question would be WHY are you creating memory management
headaches for yourself by using 'new' at all here. I suppose this
is only a simplified example from your actual application, but
chances are you are still making trouble for no reason. Never use
'new' unless you have explored the alternatives and nothing easier
will do the job.
Nov 28 '07 #4
On Nov 28, 5:57 pm, David Harmon <sou...@netcom.comwrote:
On Wed, 28 Nov 2007 03:44:32 -0800 (PST) in comp.lang.c++,
maj...@majsta.net wrote,
// this constuctor does not work
C(int ii) {
int *pI = new int(ii);
}
As others have written, it is completely wrong to declare a local
variable here that is named the same as your member variable.
No one said that it was completely wrong. It's generally
considered bad style, because it is confusing to the reader, but
it is legal. In the case of constructors, in fact, it's not
that exceptional to give the argument (which also acts as a
local variable) the same name as the member.
But it's still wrong to use assignment instead of construction to
build member variables. Not that there is much difference in the
case of ints, but what you have should still be written as:
C(int ii) : pI(new int(ii)) {
}

Then next question would be WHY are you creating memory management
headaches for yourself by using 'new' at all here. I suppose this
is only a simplified example from your actual application, but
chances are you are still making trouble for no reason. Never use
'new' unless you have explored the alternatives and nothing easier
will do the job.
It's not always that simple. The usual reason for dynamic
allocation in such cases is polymorphism. And it's not always
possible to determine the desired actual type with a single
expression.

(In such cases, it's certainly worth considering using something
like boost::scoped_ptr for the member. If there's more than one
such pointer, you must consider some sort of special pointer
management.)

--
James Kanze (GABI Software) email:ja*********@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34
Nov 29 '07 #5

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

Similar topics

3
by: Joe | last post by:
Hi, I have been struggling with this issue for a couple of days and would like to know if some can give me a pointer. I want to initialize a struct with default values and depending on the...
4
by: Mantorok Redgormor | last post by:
Is this legal? int foo = { 0 }; gcc gives: foo.c: In function `main': foo.c:5: warning: missing braces around initializer foo.c:5: warning: (near initialization for `foo') foo.c:5:...
1
by: qwerty2_reverse_iterator | last post by:
Is this a bug with the ms compiler (V7.1)? (It seems so at least.) I get errors when I don't initialize all the const pointer fields of an anonymous union in a struct. Example: //T2.h...
17
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...
5
by: vivekian | last post by:
Hi , Have a class where a private member is a reference member which needs to be initialized when the constructor is called. The compiler rightly will not allow this. Is there some way to...
6
by: alacrite | last post by:
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?
13
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...
3
by: Ramesh | last post by:
Hi, I am trying to create an array of pointers to member functions inside my class. When I created a global array of type pfn & initialized with member functions and copy it back to the member...
27
by: Nate Eldredge | last post by:
Consider the following pseudo-code: #include <opaque.h> struct foo { int a; opaque_t op; int b; };
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
0
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...

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.