473,811 Members | 2,963 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

pointer to a class

Hi all, I have a question about the code below. Any idea abuot that,
thanks in advance!

myclass.h
class myclass
{
public:
myclass();
~myclass();
void setdata();

private:
yclass *ypr;
};

myclass.cpp
include"myclass .h"
include"yclass. h"

myclass::myclas s()
{
yclass *ypr=new yclass;
}

myclass::~mycla ss()
{
delete ypr;
}

void myclass::setdat a()
{
yclass *newpr=new yclass;
ypr=newpr; //My question is here. If I delete the "*ypr" pointer in
the destructor function of myclass, does the "*newpr" pointer being
deleted automatically since both of them have the same address? the
newpr class object has the same lifetime as myclass(after it was
created), and I have no idea when it should be deleted.
}

Jul 23 '05 #1
7 1576
an*****@hotmail .com wrote:
My question is here. If I delete the "*ypr" pointer in
the destructor function of myclass, does the "*newpr" pointer being
deleted automatically since both of them have the same address?
They don't have the same address. myclass::yptr points to one instance
of a yclass, and newpr points to another instance of yclass. General
rule of thumb: you need 1 call to 'delete' for every call to 'new'.
You have 2 calls to 'new', but only 1 call to 'delete'. Memory leak.
the newpr class object has the same lifetime as myclass(after it was
created), and I have no idea when it should be deleted.


Do you really need to instantiate the yclass outside of myclass' ctor?
Just let myclass manage it's own resources.

Take care,

John Dibling

Jul 23 '05 #2

<an*****@hotmai l.com> wrote in message
news:11******** **************@ g47g2000cwa.goo glegroups.com.. .
Hi all, I have a question about the code below. Any idea abuot that,
thanks in advance!

myclass.h
class myclass
{
public:
myclass();
~myclass();
void setdata();

private:
yclass *ypr;
};

myclass.cpp
include"myclass .h"
include"yclass. h"

myclass::myclas s()
{
yclass *ypr=new yclass;
That should be just

ypr = new yclass;

As it is, you're declaring (and then leaking) new local variable, not
setting the value of the member.
}

myclass::~mycla ss()
{
delete ypr;
}

void myclass::setdat a()
{
yclass *newpr=new yclass;
ypr=newpr; //My question is here. If I delete the "*ypr" pointer in
the destructor function of myclass, does the "*newpr" pointer being
deleted automatically since both of them have the same address? the
newpr class object has the same lifetime as myclass(after it was
created), and I have no idea when it should be deleted.
}


The variable newpr is not a "class object", it's a pointer. There is just
one object here, and it is deleted when *any* pointer to it is deleted. But
when this function ends, the local newpr pointer is not deleted, it goes out
of scope, and simply doesn't exist any more. The object it pointed to lives
on, and in this case is now pointed to by the ypr member pointer. (So, you
don't have to worry about calling delete for it.)

But...why are you using the temporary at all? Why not just "ypr = new
yclass;"?

However!!! Notice that whatever ypr pointed to before you ran this function
is now leaked (i.e., it never gets destroyed). If you want to change what
ypr points to, you need to first delete ypr, then assign it a new instance
of yclass.

A note on your style: generally, a function with a name like "setdata" would
be passed whatever data it is you want to "set". The name is somewhat
misleading, if what it's doing is creating a new yclass member.

Finally, read up on the "rule of three". Whenever you have a dynamic member
(a pointer) like this, it's likely that you'll need a copy constructor and
an assignment operator as well.

-Howard
Jul 23 '05 #3

"John Dibling" <jd******@gmail .com> wrote in message
news:11******** **************@ g49g2000cwa.goo glegroups.com.. .
an*****@hotmail .com wrote:
My question is here. If I delete the "*ypr" pointer in
the destructor function of myclass, does the "*newpr" pointer being
deleted automatically since both of them have the same address?
They don't have the same address. myclass::yptr points to one instance
of a yclass, and newpr points to another instance of yclass. General
rule of thumb: you need 1 call to 'delete' for every call to 'new'.
You have 2 calls to 'new', but only 1 call to 'delete'. Memory leak.


Well, they do point to the same address after this code:
yclass *newpr=new yclass;
ypr=newpr;


But, the problem is that ypr already pointed to something *before* this
code, and *that* object was leaked by simply assigning it a new value,
without deleting the existing object first.

(Just wanted to clarify where the leak occurred.)

-Howard

Jul 23 '05 #4
an*****@hotmail .com wrote:
Hi all, I have a question about the code below. Any idea abuot that,
thanks in advance!

myclass.h
class myclass
{
public:
myclass();
~myclass();
void setdata();

private:
yclass *ypr;
};

myclass.cpp
include"myclass .h"
include"yclass. h"
This shouldn't compile, because yclass in unknown in myclass.h.
myclass::myclas s()
{
yclass *ypr=new yclass;
}
This defines a new local pointer in the constructor and initializes it with
the address of a new dynamically allocated object. Then, the constructor
finishes, the pointer goes out of scope, and the dynamic object becomes a
memory leak, because you lost the only pointer to it.
Probably, you rather want something like:

myclass::myclas s()
: ypr(new yclass)
{
}
myclass::~mycla ss()
{
delete ypr;
}

void myclass::setdat a()
{
yclass *newpr=new yclass;
ypr=newpr; //My question is here. If I delete the "*ypr" pointer in
the destructor function of myclass, does the "*newpr" pointer being
deleted automatically since both of them have the same address? the
newpr class object has the same lifetime as myclass(after it was
created), and I have no idea when it should be deleted.
}


You seem to be confusing the pointers with the objects they point to. If you
change the constructor like I wrote above, ypr already points to an object
of class yclass. So what happens in setdata is the following:
You create a second object of class yclass and initialize newpr with it.
Then you let ypr point to that same new object. Then the function ends and
newpr (only the pointer itself, nothing else) gets out of scope. So ypr now
points to the newly created object. When your myclass object gets
destroyed, its destructor will delete that one.
However, there is still the object that ypr has been pointing to before
setdata was called. Since you overwrote ypr with the address of another
object, the old object is lost. You don't have any pointer to it anymore,
so you can never delete it anymore.
So what you have to do is delete the old object within setdata:

void myclass::setdat a()
{
yclass *newpr=new yclass;
delete ypr;
ypr=newpr;
}

Jul 23 '05 #5
an*****@hotmail .com wrote:
Hi all, I have a question about the code below. Any idea abuot that,
thanks in advance!

myclass.h
class myclass
{
public:
myclass();
~myclass();
void setdata();

private:
yclass *ypr;
};

myclass.cpp
include"myclass .h"
include"yclass. h"

myclass::myclas s()
{
yclass *ypr=new yclass;
This is a HUGE mistake. You declare a _local_ variable 'ypr', which
_hides_ the member 'ypr'. You may think you are assigning the result
of using 'new' to the 'this->ypr', but you actually aren't. The
declaration of the member 'ypr' is in the class definition. Drop the
'yclass *' here if you actually want to assign to the member. Better
yet, use _initialisation _ instead (read about "initiliase r lists" in
your favourite C++ book).
}

myclass::~mycla ss()
{
delete ypr;
}
Clear violation of "the Rule of Three". Read about it in archives.
void myclass::setdat a()
{
yclass *newpr=new yclass;
ypr=newpr; //My question is here. If I delete the "*ypr" pointer in
the destructor function of myclass, does the "*newpr" pointer being
deleted automatically since both of them have the same address?
They don't have the same address. The have the same value. The 'newpr'
local variable carries the value to 'ypr' and is then discarded. You
can forget 'newpr', it's superfluous anyway. You could simply write

ypr = new yclass;

here instead of the two statements.
the
newpr class object has the same lifetime as myclass(after it was
created), and I have no idea when it should be deleted.
There is no such thing as "newpr class object". 'newpr' is but
a pointer that has the value equal to the address of a dynamically
allocated 'yclass' object. You don't need to delete 'newpr' since
its value is assigned (and therefore owned) by 'ypr' in this function.
}


Let me make one more comment. OK, two. First, you need to understand
pointers before you attempt dynamic memory management. How you do it
is up to you. I suggest exploring addresses of real objects created
statically or automatically, but not dynamically. Pass the pointers
to functions, pass objects to functions, query the addresses of those
objects and the contents. See more books (than you have already seen).
Second, you have a memory leak in the 'setdata' member function. The
'ypr' pointer's old value that used to holds the address of another
dynamically allocated object, is lost when you assign another value to
it. So, the dynamic 'yclass' object, which you allocated in the
constructor, is hanging around forever, and you can't do anything about
it because you don't have its address any more.

V
Jul 23 '05 #6

"Rolf Magnus" <ra******@t-online.de> wrote in message
news:d9******** *****@news.t-online.com...
So what you have to do is delete the old object within setdata:

void myclass::setdat a()
{
yclass *newpr=new yclass;
delete ypr;
ypr=newpr;
}


Or just

void myclass::setdat a()
{
delete ypr;
ypr = new yclass;
}

No need for a temporary.

-Howard
Jul 23 '05 #7
Howard wrote:
void myclass::setdat a()
{
yclass *newpr=new yclass;
delete ypr;
ypr=newpr;
}


Or just

void myclass::setdat a()
{
delete ypr;
ypr = new yclass;
}

No need for a temporary.


Well, it depends on how robust you want your code. Think what happens if the
operator new or yclass's constructor throws an exception.

Jul 23 '05 #8

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

Similar topics

2
2271
by: lawrence | last post by:
I had some code that worked fine for several weeks, and then yesterday it stopped working. I'm not sure what I did. Nor can I make out why it isn't working. I'm running a query that should return 3 items from the database. I then get a count of the return, which correctly tells me that I've got 3 items. I then go into a for loop which I expect to loop 3 times and print out the 3 items. Here is where things get strange: it loops 3 times and...
5
2037
by: lawrence | last post by:
I posted before, but have now narrowed my problem down to this method. At the start of the method, I test to make sure that I have a resource, a pointer to data returned from a database. This test is coming back true, so the next line runs, which attempts to get the next row from the dataset. This brings back nothing. On the queries I'm running right now, the first row will be fetched, but then no further rows. If I expect 20 rows back, I...
2
2345
by: Asfand Yar Qazi | last post by:
Hello. Partly for learning purposes, I have written a smart pointer class. Could you please tell me what's wrong with it? (I know there's something wrong with it, but just not what!) Note that, as well as reference counting the stored pointer, it also has the ability to be declared for incomplete types (I think). I.e.: struct Incomplete;
4
2147
by: Carsten Spieß | last post by:
Hello all, i have a problem with a template constructor I reduced my code to the following (compiled with gcc 2.7.2) to show my problem: // a base class class Base{}; // two derived classes
6
2295
by: Itay_k | last post by:
Hello, I want a member in my class that will save pointer to pointer to System::Drawing::Image class. When I write on my class code: System::Drawing::Image **bmp; I get this error message: error C3160: 'bmp' : cannot declare interior __gc pointer or reference as a
2
35638
weaknessforcats
by: weaknessforcats | last post by:
Handle Classes Handle classes, also called Envelope or Cheshire Cat classes, are part of the Bridge design pattern. The objective of the Bridge pattern is to separate the abstraction from the implementation so the two can vary independently. Handle classes usually contain a pointer to the object implementation. The Handle object is used rather than the implemented object. This leaves the implemented object free to change without affecting...
7
3818
by: WaterWalk | last post by:
Hello. I thought I understood member function pointers, but in fact I don't. Consider the following example: class Base { public: virtual ~Base() {} }; class Derived : public Base {
5
4666
by: Tim Frink | last post by:
Hi, I'm experimenting with function pointers and found two questions. Let's assume this code: 1 #include <iostream> 2 class A; 3 4 //////////////////////////////////////////// 5 class B
5
3656
by: Immortal Nephi | last post by:
I would like to design an object using class. How can this class contain 10 member functions. Put 10 member functions into member function pointer array. One member function uses switch to call 10 member functions. Can switch be replaced to member function pointer array? Please provide me an example of source code to show smart pointer inside class. Thanks....
8
1864
by: mathieu | last post by:
Hi there I have implemented a very simple smartpointer class (invasive design). And I was wondering what should be the natural API when using those in a Container. I choose to define the following operator in my smartpointer class: .... operator ObjectType * () const
0
9603
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
10644
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
10379
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...
0
10124
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...
1
7664
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
6882
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
5690
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4334
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
3
3015
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.