473,771 Members | 2,328 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Execution Problem w/memory object

This is a short program that I have written from a text that
demonstrates a class object variable created on the stack memory and
another class object variable created on the heap memory. By way of
the text, the program is supposed to demonstrate the use of a copy
constructor function for the object created on the heap (because there
is a char* pointer variable in the instantiated class) and how you
would use the delete keyword with the object and to also use a
destructor for the char* pointer variable which is also placed on the
heap memory when instantiated - this being becuase the heap memory
will not be freed when the main function goes out of scope, as with
the class object variable declared on the stack memory does by default
constructor.

The program is exactly as demonstrated in the text - WHY the problem?
Thank you in advance.

//interface file Stocks.h
#if !defined(STOCKS _H)
#define STOCKS_H

class Stocks
{
public:
Stocks();//default constructor
Stocks(char* szName);//parameterized constructor
Stocks(const Stocks&);//copy constructor declaration
~Stocks();//destructor
//accessor function declarations
void setStockName(ch ar* szName);
void setNumShares(in t);
void setPricePerShar e(double);
char* getStockName() const;
int getNumShares() const;
double getPricePerShar e() const;
double calcTotalValue( );
private:
//declare private data members
char* szStockName;//declares character array pointer
int iNumShares;
double dCurrentValue;
double dPricePerShare;
};

#endif
//end class Stocks.h

///////////////////////////////////////////
//implementation file Stocks.cpp

#include "Stocks.h"
#include <string.h>
#include <ostream.h>

Stocks::Stocks( )//defines default constructor
{
char* szStockName = new char[25];
strcpy(szStockN ame,"");
iNumShares = 0;
dCurrentValue = 0;
dPricePerShare = 0;
};

Stocks::Stocks( char* szName)//defines parameterized constructor
{
char* szStockName = new char[25];
strcpy(szStockN ame,szName);
iNumShares = 0;
dCurrentValue = 0;
dPricePerShare = 0;
};

Stocks::Stocks( const Stocks& sourceStock)//copy constructor definition
{
szStockName = new char[25];
strcpy(szStockN ame, sourceStock.szS tockName);
};

Stocks::~Stocks ()//destructor definition
{
delete[] szStockName;
cout << "Destructor called." << endl;

};
void Stocks::setStoc kName(char* szName)
{
strcpy(szStockN ame,szName);
}

void Stocks::setNumS hares(int iShares)
{
iNumShares = iShares;
}

void Stocks::setPric ePerShare(doubl e dPrice)
{
dPricePerShare = dPrice;
}

char* Stocks::getStoc kName() const
{
return szStockName;
}

int Stocks::getNumS hares(void)cons t
{
return iNumShares;
}

double Stocks::getPric ePerShare()cons t
{
return dPricePerShare;
}

double Stocks::calcTot alValue()
{
dCurrentValue = iNumShares * dPricePerShare;
return dCurrentValue;
}
//end Stocks.cpp
//////////////////////////////////

//client source file used to instantiate custom class objects
//Shares.cpp
#include "Stocks.h"
#include <iostream>
#include <string>
#include <iomanip>//for use of setprecision() and setiosflags()
using namespace std;

void main()
{
cout << "\t\t\t\t\b\bSt ock Portfolio" << endl << endl
<< "This program displays the current values of stock you have
purchased for" << endl
<< "both Cisco and Lucent Technologies." << endl << endl;

//declares class object variable and passes value to parameterized
constructor
Stocks stockPick1("Cis co");

//heap memory object that passes literal string to parameterized
constructor
Stocks* stockPick2 = new Stocks("Lucent" );
/*use indirection operator associated with heap memory object to
access
class method and pass literal numeric value*/
stockPick2->setNumShares(2 00);
stockPick2->setPricePerSha re(59.5);

//format numeric output in fixed notation with two decimals
cout << setprecision(2) << setiosflags(ios ::fixed | ios::showpoint) ;
cout << "The current value of your stock in " <<
stockPick1.getS tockName()
<< " is $" << stockPick1.calc TotalValue() << "." << endl;

cout << "The current value of your stock in " <<
stockPick2->getStockName ()
<< " is $" << stockPick2->calcTotalValue () << "." << endl;

delete stockPick2;//manually delete the object from the heap memory

}//end main
Jul 22 '05 #1
5 1777
On 13 Sep 2004 21:17:08 -0700, an*********@hot mail.com (August1) wrote
in comp.lang.c++:
This is a short program that I have written from a text that
demonstrates a class object variable created on the stack memory and
another class object variable created on the heap memory. By way of
the text, the program is supposed to demonstrate the use of a copy
constructor function for the object created on the heap (because there
is a char* pointer variable in the instantiated class) and how you
would use the delete keyword with the object and to also use a
destructor for the char* pointer variable which is also placed on the
heap memory when instantiated - this being becuase the heap memory
will not be freed when the main function goes out of scope, as with
the class object variable declared on the stack memory does by default
constructor.

The program is exactly as demonstrated in the text - WHY the problem?
Thank you in advance.
Either the text is wrong, or you copied it incorrectly.
//interface file Stocks.h
#if !defined(STOCKS _H)
#define STOCKS_H

class Stocks
{
public:
Stocks();//default constructor
Stocks(char* szName);//parameterized constructor
Stocks(const Stocks&);//copy constructor declaration
~Stocks();//destructor
//accessor function declarations
void setStockName(ch ar* szName);
void setNumShares(in t);
void setPricePerShar e(double);
char* getStockName() const;
int getNumShares() const;
double getPricePerShar e() const;
double calcTotalValue( );
private:
//declare private data members
char* szStockName;//declares character array pointer
int iNumShares;
double dCurrentValue;
double dPricePerShare;
};

#endif
//end class Stocks.h

///////////////////////////////////////////
//implementation file Stocks.cpp

#include "Stocks.h"
#include <string.h>
The recommended name for this C header in standard C++ is <cstring>.
#include <ostream.h>
This header is not part of standard C++ at all. It should be
<ostream>.
Stocks::Stocks( )//defines default constructor
{
char* szStockName = new char[25];
The pointer to char _defined_ above is a local automatic variable of
the this function. It hides the class member of the same name, which
could only be accessed by using this->szStockName. So you end up
leaving the member uninitialized. The local variable goes out of
scope at the end of the constructor without the memory ever being
deleted, causing a memory leak.

Remove the 'char *' from in front of szStockName and you will be
allocating memory to the member variable with that name, instead of
hiding it.
strcpy(szStockN ame,"");
iNumShares = 0;
dCurrentValue = 0;
dPricePerShare = 0;
};

Stocks::Stocks( char* szName)//defines parameterized constructor
{
char* szStockName = new char[25];
The same thing applies here. Eliminate the 'char *' in front of the
pointer.
strcpy(szStockN ame,szName);
iNumShares = 0;
dCurrentValue = 0;
dPricePerShare = 0;
};

Stocks::Stocks( const Stocks& sourceStock)//copy constructor definition
{
szStockName = new char[25];
Note that in this constructor you got it right.
strcpy(szStockN ame, sourceStock.szS tockName);
};

Stocks::~Stocks ()//destructor definition
{
delete[] szStockName;
cout << "Destructor called." << endl;

};
void Stocks::setStoc kName(char* szName)
{
strcpy(szStockN ame,szName);
}

void Stocks::setNumS hares(int iShares)
{
iNumShares = iShares;
}

void Stocks::setPric ePerShare(doubl e dPrice)
{
dPricePerShare = dPrice;
}

char* Stocks::getStoc kName() const
{
return szStockName;
}

int Stocks::getNumS hares(void)cons t
{
return iNumShares;
}

double Stocks::getPric ePerShare()cons t
{
return dPricePerShare;
}

double Stocks::calcTot alValue()
{
dCurrentValue = iNumShares * dPricePerShare;
return dCurrentValue;
}
//end Stocks.cpp
//////////////////////////////////

//client source file used to instantiate custom class objects
//Shares.cpp
#include "Stocks.h"
#include <iostream>
#include <string>
#include <iomanip>//for use of setprecision() and setiosflags()
using namespace std;

void main()
You were doing pretty good up until now. The C++ standard requires
that main() be defined with a return type of int. "void main()" is
not, and never has been, legal C++. No matter what some illiterate
compilers chose to promote.
{
cout << "\t\t\t\t\b\bSt ock Portfolio" << endl << endl
<< "This program displays the current values of stock you have
purchased for" << endl
<< "both Cisco and Lucent Technologies." << endl << endl;

//declares class object variable and passes value to parameterized
constructor
Stocks stockPick1("Cis co");

//heap memory object that passes literal string to parameterized
constructor
Stocks* stockPick2 = new Stocks("Lucent" );
/*use indirection operator associated with heap memory object to
access
class method and pass literal numeric value*/
stockPick2->setNumShares(2 00);
stockPick2->setPricePerSha re(59.5);

//format numeric output in fixed notation with two decimals
cout << setprecision(2) << setiosflags(ios ::fixed | ios::showpoint) ;
cout << "The current value of your stock in " <<
stockPick1.getS tockName()
<< " is $" << stockPick1.calc TotalValue() << "." << endl;

cout << "The current value of your stock in " <<
stockPick2->getStockName ()
<< " is $" << stockPick2->calcTotalValue () << "." << endl;

delete stockPick2;//manually delete the object from the heap memory

}//end main


--
Jack Klein
Home: http://JK-Technology.Com
FAQs for
comp.lang.c http://www.eskimo.com/~scs/C-faq/top.html
comp.lang.c++ http://www.parashift.com/c++-faq-lite/
alt.comp.lang.l earn.c-c++
http://www.contrib.andrew.cmu.edu/~a...FAQ-acllc.html
Jul 22 '05 #2
>
Either the text is wrong, or you copied it incorrectly.


Hi Jack,
Thanks for the expedient response. No, I did not copy anything
errantly and believe me I tried a few changes before re-reading the
text allocated to memory management. I was already well on my way to
the changes you have highlighted and discussed.
Yes, I am well informed that C++ uses the int main() function
rather than void main(). Here is what I don't really appreciate, I
suppose, Why are the majority of authors who are submitting texts that
are approved for tutorials or educational purposes adhering to and
promoting the void main() approach, without even mentioning the int
main() standard???
How should this normally be remedied, by adding a return statement
with int main()? If this is the approach, what is the ususal return
value?

Thanks again?
Jul 22 '05 #3
August1 wrote:

Either the text is wrong, or you copied it incorrectly.

Hi Jack,
Thanks for the expedient response. No, I did not copy anything
errantly and believe me I tried a few changes before re-reading the
text allocated to memory management. I was already well on my way to
the changes you have highlighted and discussed.
Yes, I am well informed that C++ uses the int main() function
rather than void main(). Here is what I don't really appreciate, I
suppose, Why are the majority of authors who are submitting texts that
are approved for tutorials or educational purposes adhering to and
promoting the void main() approach, without even mentioning the int
main() standard???


Because they don't know.
Because a major company used void main() throught their whole
documentation
Because those instuctors think that this major company is god and defines
the language
....
How should this normally be remedied, by adding a return statement
with int main()? If this is the approach, what is the ususal return
value?


for main() there is an exception:
You don't need to return anything. In this case the
compiler has to insert a
return 0;
for you. But beware: main() is the only place where you can do
this. In every other function with a return value it is prohibited
to not actually return something.

Other return values are

return EXIT_SUCCESS
return EXIT_FAILURE
BTW: Online tutorial aren't a good way to learn the language. As you have
seen, most of them are full of errors of the simplest type and work
just by accident. Also: How do you know that the guy who wrote the
tutorial knows what he is talking about?

Get a good book. See the FAQ for recommendations .
http://ma.rtij.nl/acllc-c++.FAQ.html

--
Karl Heinz Buchegger
kb******@gascad .at
Jul 22 '05 #4
Karl Heinz Buchegger <kb******@gasca d.at> wrote in message news:<41******* ********@gascad .at>...
August1 wrote:

Either the text is wrong, or you copied it incorrectly.


Hi Jack,
Thanks for the expedient response. No, I did not copy anything
errantly and believe me I tried a few changes before re-reading the
text allocated to memory management. I was already well on my way to
the changes you have highlighted and discussed.
Yes, I am well informed that C++ uses the int main() function
rather than void main(). Here is what I don't really appreciate, I
suppose, Why are the majority of authors who are submitting texts that
are approved for tutorials or educational purposes adhering to and
promoting the void main() approach, without even mentioning the int
main() standard???


Because they don't know.
Because a major company used void main() throught their whole
documentation
Because those instuctors think that this major company is god and defines
the language
...
How should this normally be remedied, by adding a return statement
with int main()? If this is the approach, what is the ususal return
value?


for main() there is an exception:
You don't need to return anything. In this case the
compiler has to insert a
return 0;
for you. But beware: main() is the only place where you can do
this. In every other function with a return value it is prohibited
to not actually return something.

Other return values are

return EXIT_SUCCESS
return EXIT_FAILURE
BTW: Online tutorial aren't a good way to learn the language. As you have
seen, most of them are full of errors of the simplest type and work
just by accident. Also: How do you know that the guy who wrote the
tutorial knows what he is talking about?

Get a good book. See the FAQ for recommendations .
http://ma.rtij.nl/acllc-c++.FAQ.html


Hi Karl,

Thank you for the follow-up. I think that I understand who the
company is that you are referencing and other matters associated with
it. I'm certain there are a number of people who are not aware that
int main() is a viable and more preferable option to use, but when
associated with the company in some form or fashion, those who are
aware of int main() may choose to promote the gospel of void main()
instead.
I think you are also saying the compiler by default inserts the
return 0 value. I have manually inserted return 0 when declaring main
of the int type to see if this was executable on previous occasions
prior to posts, and wanted to see if a program would execute without
inserting the return statement with the int main() function. The
compiler raises a warning but does allow program execution.
I also used the constants EXIT_SUCCESS and EXIT_FAILURE as return
values when using the int main() function and was pleased to see the
execution desired. I will probably go with either of the latter in
subsequent programs and use the int main() function from this point
on.
Also, where are EXIT_SUCCESS and EXIT_FAILURE defined, and on what
level does the benefit arise when using int main() as opposed to void
main()? This seems to be a strong point many C - C++ programmers
continuously raise when discussing the language.
Lastly, I do not know that the individual who authored the text is
one of the better concerning this language. I have not found his code
to be errant until raising the matters stated within these posts
(perhaps typo error regarding the char* array pointers defined in the
constructor functions, exlcluding void main()), and he is also
associated with the course.com Web site, which I think tries to do a
legitimate service. This particular text, as many associated with this
Web site, is published by Course Technology of Thomson Learning. It
may be that there is a strong MS flavor associated with this site that
I really am not qualified to comment on.

Again, thanks for your input.
Anthony
Jul 22 '05 #5
In article <fc************ **************@ posting.google. com>,
August1 <an*********@ho tmail.com> wrote:
Also, where are EXIT_SUCCESS and EXIT_FAILURE defined, and on what
level does the benefit arise when using int main() as opposed to void
main()? This seems to be a strong point many C - C++ programmers
continuously raise when discussing the language.


Check out http://www.comeaucomputing.com/techtalk/#voidmain
http://www.comeaucomputing.com/techtalk/#mainexit
http://www.comeaucomputing.com/techt...aintermination
--
Greg Comeau / Comeau C++ 4.3.3, for C++03 core language support
Comeau C/C++ ONLINE ==> http://www.comeaucomputing.com/tryitout
World Class Compilers: Breathtaking C++, Amazing C99, Fabulous C90.
Comeau C/C++ with Dinkumware's Libraries... Have you tried it?
Jul 22 '05 #6

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

Similar topics

30
2578
by: Sean R. Lynch | last post by:
I've been playing around with Zope's RestrictedPython, and I think I'm on the way to making the modifications necessary to create a capabilities-based restricted execution system. The idea is to strip out any part of RestrictedPython that's not necessary for doing capabilities and do all security using just capabilities. The basic idea behind capabilities is that you don't give any piece of code you don't trust a reference to something...
4
1835
by: August1 | last post by:
i'm having difficulties with the execution of a program, i believe due to something i am missing in the copy constructor implementation. When i create one object of the class and run the program with that object alone, there are no problems. however, when subsequently using the copy constructor for a second object and/or a third object created on the heap memory - i run into an execution problem and assert failure dialog box (ignore,...
38
2565
by: vashwath | last post by:
Might be off topic but I don't know where to post this question.Hope some body clears my doubt. The coding standard of the project which I am working on say's not to use malloc.When I asked my lead(I have just started working) he said we should not use dynamic allocation in real time systems, the code will not run in predictable time period.Can anybody tell what does he mean?Why the execution time becomes unpredictable? Thanks
17
5097
by: romixnews | last post by:
Hi, I'm facing the problem of analyzing a memory allocation dynamic and object creation dynamics of a very big C++ application with a goal of optimizing its performance and eventually also identifying memory leaks. The application in question is the Mozilla Web Browser. I also have had similar tasks before in the compiler construction area. And it is easy to come up with many more examples, where such kind of statistics can be very...
18
1931
by: Tom Cole | last post by:
I'm working on a small Ajax request library to simplify some tasks that I will be taking on shortly. For the most part everything works fine, however I seem to have some issues when running two requests at the same time. The first one stops execution as the second continues. If I place either an alert between the two requests or run the second through a setTimeout of only 1 millisecond, they both work. You can see a working example here:...
15
2209
by: polas | last post by:
Hi everyone - I have a question. I am just playing around with C (I realise there are better ways to do what I want, but I would like to do it this way to increase my understanding of C) and would like to read an executable file in to a portion of memory and then pass execution to this and execute the file. However, I can not get it working and my efforts have resulted in a Seg Fault. Below is the code I have got #include "stdio.h"
2
2032
by: -Lost | last post by:
I have been watching code execution in various situations and I have noticed something. On the first test my example gave me obvious results. One method was far faster than the other. However, upon executing the code again (without refreshing the browser) the two tests were almost identical in speed. I am not sure if this has something to do specifically with JavaScript (and/or its engine) or if this is just something browsers try...
6
2260
by: 2beagles | last post by:
So, I have not written c++ in quite a while and am trying to dig back in to it. I am running in to a weird situation and I am hoping someone might be able to explain it. I have a class representing a three dimensional matrix of integers in which I am trying to implement the operator+ for addition of an integer to all elements of the matrix. The class signature looks like this, class Matrix { public: Matrix();
17
1475
by: Suresh Pillai | last post by:
I am performing simulations on networks (graphs). I have a question on speed of execution (assuming very ample memory for now). I simplify the details of my simulation below, as the question I ask applies more generally than my specific case. I would greatly appreciate general feedback in terms of computing and of course considerations specific to implementation in Python. The nodes in my network may be ON or OFF. The network starts...
0
9619
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
9454
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
10102
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
10038
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,...
1
7460
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
5354
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5482
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3609
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2850
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.