473,657 Members | 2,409 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

warning: taking address of temporary

/*
Triangle.cpp
*/

// Use a pure virtual function.

#include <iostream>
#include <cstring>
using namespace std;

// A class for two-dimensional objects.
class TwoDShape {
// these are private
double width;
double height;

// add a name field
char name[20];
public:

// Default constructor.
TwoDShape() {
width = height = 0.0;
strcpy(name, "unknown");
}

// Constructor for TwoDShape.
TwoDShape(doubl e w, double h, char *n) {
width = w;
height = h;
strcpy(name, n);
}

// Construct object with equal width and height.
TwoDShape(doubl e x, char *n) {
width = height = x;
strcpy(name, n);
}

void showDim() {
cout << "Width and height are " << width << " and " << height <<
"\n";
}

// accessor functions
double getWidth() { return width; }
double getHeight() { return height; }
void setWidth(double w) { width = w; }
void setHeight(doubl e h) { height = h; }
char *getName() { return name; }

// area() is now a pure virtual function
virtual double area() = 0;

};

// Triangle is derived from TwoDShape.
class Triangle : public TwoDShape {
char style[20]; //now private
public:

/* A default constructor. This automatically invokes
the default constructor of TwoDShape. */
Triangle() {
strcpy(style, "unknown");
}

// Constructor with three parameters.
Triangle(char *str, double w, double h)
: TwoDShape(w, h, "triangle") {
strcpy(style, str);
}

// Construct an isosceles triangle.
Triangle(double x) : TwoDShape(x, x, "triangle") {
strcpy(style, "isosceles" );
}

// This now overrides area() declared in TwoDShape.
double area() {
return getWidth() * getHeight() / 2;
}

void showStyle() {
cout << "Triangle is " << style << "\n";
}
};

int main() {
// declare an array of pointers to TwoDShape objects.
TwoDShape *shapes[4];

shapes[0] = &Triangle("righ t", 8.0, 12.0);
shapes[1] = &Triangle(3. 0);
shapes[2] = &Triangle(4. 0);
shapes[3] = &Triangle(7. 0);

for(int i=0; i < 2; i++) {
cout << "object is " <<
shapes[i]->getName() << "\n";

cout << "Area is " <<
shapes[i]->area() << "\n";

cout << "\n";
}

return 0;
}

Hi, I'm a beginning programmer. Above is the code that is giving me
the error. I have talked with a professor about this issue. The
error happens on the lines beginning "shapes[0] = ... "

The professor says, because Triangle was created without a variable
they are temporary objects. Which means they will be destroyed and
the pointer becomes a dangling pointer.

I edited the code and just created the objects and gave them a
variable to be stored in. i.e. "Triangle t1("right", 4, 5);" Then I
just do "shapes[0] = &t1;" When I recompile, I get no warnings and it
runs as expected.

My question: Is there a way so that the temporary objects are not
destroyed? Seems like a waste of memory to create a variable outside
of the array that will always be referenced through the array.

May 8 '07 #1
3 12882
On May 8, 10:58 am, dani...@digital filing.com wrote:

<snip>
My question: Is there a way so that the temporary objects are not
destroyed? Seems like a waste of memory to create a variable outside
of the array that will always be referenced through the array.
For the purpose of this example, create the Triangles with new.

shapes[0] = new Triangle(...);

shapes[0] now holds the address of the created Triangle.

If you're writing an application that does something like this, you
might want to look at std::vector and boost::shared_p tr.
May 8 '07 #2
On 2007-05-08 16:58, da*****@digital filing.com wrote:
/*
Triangle.cpp
*/

// Use a pure virtual function.

#include <iostream>
#include <cstring>
using namespace std;

// A class for two-dimensional objects.
class TwoDShape {
// these are private
double width;
double height;

// add a name field
char name[20];
public:

// Default constructor.
TwoDShape() {
width = height = 0.0;
strcpy(name, "unknown");
}

// Constructor for TwoDShape.
TwoDShape(doubl e w, double h, char *n) {
width = w;
height = h;
strcpy(name, n);
}

// Construct object with equal width and height.
TwoDShape(doubl e x, char *n) {
width = height = x;
strcpy(name, n);
}

void showDim() {
cout << "Width and height are " << width << " and " << height <<
"\n";
}

// accessor functions
double getWidth() { return width; }
double getHeight() { return height; }
void setWidth(double w) { width = w; }
void setHeight(doubl e h) { height = h; }
char *getName() { return name; }

// area() is now a pure virtual function
virtual double area() = 0;

};

// Triangle is derived from TwoDShape.
class Triangle : public TwoDShape {
char style[20]; //now private
public:

/* A default constructor. This automatically invokes
the default constructor of TwoDShape. */
Triangle() {
strcpy(style, "unknown");
}

// Constructor with three parameters.
Triangle(char *str, double w, double h)
: TwoDShape(w, h, "triangle") {
strcpy(style, str);
}

// Construct an isosceles triangle.
Triangle(double x) : TwoDShape(x, x, "triangle") {
strcpy(style, "isosceles" );
}

// This now overrides area() declared in TwoDShape.
double area() {
return getWidth() * getHeight() / 2;
}

void showStyle() {
cout << "Triangle is " << style << "\n";
}
};

int main() {
// declare an array of pointers to TwoDShape objects.
TwoDShape *shapes[4];

shapes[0] = &Triangle("righ t", 8.0, 12.0);
shapes[1] = &Triangle(3. 0);
shapes[2] = &Triangle(4. 0);
shapes[3] = &Triangle(7. 0);

for(int i=0; i < 2; i++) {
cout << "object is " <<
shapes[i]->getName() << "\n";

cout << "Area is " <<
shapes[i]->area() << "\n";

cout << "\n";
}

return 0;
}

Hi, I'm a beginning programmer. Above is the code that is giving me
the error. I have talked with a professor about this issue. The
error happens on the lines beginning "shapes[0] = ... "

The professor says, because Triangle was created without a variable
they are temporary objects. Which means they will be destroyed and
the pointer becomes a dangling pointer.

I edited the code and just created the objects and gave them a
variable to be stored in. i.e. "Triangle t1("right", 4, 5);" Then I
just do "shapes[0] = &t1;" When I recompile, I get no warnings and it
runs as expected.

My question: Is there a way so that the temporary objects are not
destroyed? Seems like a waste of memory to create a variable outside
of the array that will always be referenced through the array.
The simplest (as in requires the least change in the code) way to do
this is to use new to allocate the Triangles on the heap (dynamic
memory). Objects created with new will continue to exist until they are
explicitly deleted (even if you no longer have a pointer or reference to
them!). This means that when you no longer need an object created with
new you must delete them or your program will use up all memory.

To create a Triangle using new do this:

shapes[0] = new Triangle("right ", 8.0, 12.0);

And when you are done with it you use delete to delete them:

delete shapes[0];

I guess that you have not discusses dynamic memory in class, beware that
there are some problems with it if you are not careful and it is
therefore generally a good idea not to use it, but sometimes you have to.

--
Erik Wikström
May 8 '07 #3
On May 8, 11:28 am, Erik Wikström <Erik-wikst...@telia. comwrote:
On 2007-05-08 16:58, dani...@digital filing.com wrote:


/*
Triangle.cpp
*/
// Use a pure virtual function.
#include <iostream>
#include <cstring>
using namespace std;
// A class for two-dimensional objects.
class TwoDShape {
// these are private
double width;
double height;
// add a name field
char name[20];
public:
// Default constructor.
TwoDShape() {
width = height = 0.0;
strcpy(name, "unknown");
}
// Constructor for TwoDShape.
TwoDShape(doubl e w, double h, char *n) {
width = w;
height = h;
strcpy(name, n);
}
// Construct object with equal width and height.
TwoDShape(doubl e x, char *n) {
width = height = x;
strcpy(name, n);
}
void showDim() {
cout << "Width and height are " << width << " and " << height <<
"\n";
}
// accessor functions
double getWidth() { return width; }
double getHeight() { return height; }
void setWidth(double w) { width = w; }
void setHeight(doubl e h) { height = h; }
char *getName() { return name; }
// area() is now a pure virtual function
virtual double area() = 0;
};
// Triangle is derived from TwoDShape.
class Triangle : public TwoDShape {
char style[20]; //now private
public:
/* A default constructor. This automatically invokes
the default constructor of TwoDShape. */
Triangle() {
strcpy(style, "unknown");
}
// Constructor with three parameters.
Triangle(char *str, double w, double h)
: TwoDShape(w, h, "triangle") {
strcpy(style, str);
}
// Construct an isosceles triangle.
Triangle(double x) : TwoDShape(x, x, "triangle") {
strcpy(style, "isosceles" );
}
// This now overrides area() declared in TwoDShape.
double area() {
return getWidth() * getHeight() / 2;
}
void showStyle() {
cout << "Triangle is " << style << "\n";
}
};
int main() {
// declare an array of pointers to TwoDShape objects.
TwoDShape *shapes[4];
shapes[0] = &Triangle("righ t", 8.0, 12.0);
shapes[1] = &Triangle(3. 0);
shapes[2] = &Triangle(4. 0);
shapes[3] = &Triangle(7. 0);
for(int i=0; i < 2; i++) {
cout << "object is " <<
shapes[i]->getName() << "\n";
cout << "Area is " <<
shapes[i]->area() << "\n";
cout << "\n";
}
return 0;
}
Hi, I'm a beginning programmer. Above is the code that is giving me
the error. I have talked with a professor about this issue. The
error happens on the lines beginning "shapes[0] = ... "
The professor says, because Triangle was created without a variable
they are temporary objects. Which means they will be destroyed and
the pointer becomes a dangling pointer.
I edited the code and just created the objects and gave them a
variable to be stored in. i.e. "Triangle t1("right", 4, 5);" Then I
just do "shapes[0] = &t1;" When I recompile, I get no warnings and it
runs as expected.
My question: Is there a way so that the temporary objects are not
destroyed? Seems like a waste of memory to create a variable outside
of the array that will always be referenced through the array.

The simplest (as in requires the least change in the code) way to do
this is to use new to allocate the Triangles on the heap (dynamic
memory). Objects created with new will continue to exist until they are
explicitly deleted (even if you no longer have a pointer or reference to
them!). This means that when you no longer need an object created with
new you must delete them or your program will use up all memory.

To create a Triangle using new do this:

shapes[0] = new Triangle("right ", 8.0, 12.0);

And when you are done with it you use delete to delete them:

delete shapes[0];

I guess that you have not discusses dynamic memory in class, beware that
there are some problems with it if you are not careful and it is
therefore generally a good idea not to use it, but sometimes you have to.

--
Erik Wikström- Hide quoted text -

- Show quoted text -
Yes the suggestion of using the new keyword solves the issue. Thanks
for the response.

I am actually taking a refresher on C++ and dynamic memory has not
been discussed yet. But I do recall the dangers of it. Again thanks
for the help!

May 8 '07 #4

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

Similar topics

5
2497
by: Adrian | last post by:
Hi all, I am getting a warning compiling the following code using Borland C++ Builder 6, but I dont think I am doing anything wrong. When using g++ I get no warnings at all with a g++ -Wall -ansi -pedantic. Now I usually assume the compiler is correct but in this case I am not sure. push 1 gives the warning the other 2 go through fine.
4
3138
by: jt | last post by:
I'm getting a compiler error: warning C4172: returning address of local variable or temporary Here is the function that I have giving this error: I'm returning a temporary char string and its not liking it. How can I fix this? char *dequeue(struct node **first) { char temp;
32
2345
by: Stephen | last post by:
Is there a standard way to remove the warning that a C compiler might produce from the statement: if (a = b) {} I don't want to do: if ((a = b) != 0) {} Because my "a = b" is actually contained in a macro that might be used
29
1989
by: Daniel Rudy | last post by:
Hello, Consider the following code fragment: fileptr = fopen(param->filename, "r"); if (fileptr == NULL) { error("digest.c: digest_file: Open File ", errno); return(-2); }
17
3240
by: I.M. !Knuth | last post by:
Hi. I'm more-or-less a C newbie. I thought I had pointers under control until I started goofing around with this: ================================================================================ /* A function that returns a pointer-of-arrays to the calling function. */ #include <stdio.h> int *pfunc(void);
17
10265
by: Henning Hasemann | last post by:
I have a function which gets the adress of an object as argument. It does some comparsion with the object's contents and then returns. no Reference or pointer to the object is stored or will be used after the function has returned. Say the function whould be named f and the objects class whould be T it'll look like this: bool f(T* thing) { return thing->foobar == 5; // Just a stupid example
4
2943
by: rsa_net_newbie | last post by:
Hi there, I have a Managed C++ object (in a DLL) which has a method that is defined like ... Generic::List<String^>^ buildList(String^ inParm) Now, when I compile it, I get "warning C4172: returning address of local variable or temporary". In good old 'C', that would indicate that a 'static' was missing from the declaration of the returned value.
0
574
by: daniell | last post by:
/* Triangle.cpp */ // Use a pure virtual function. #include <iostream> #include <cstring> using namespace std;
2
2365
by: anon.asdf | last post by:
Hello! 1) =============================== When trying to define an array of std::string ... func( (std::string ) { std::string("ab"), std::string("cd"), std::string("ef") } , 3 ); ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ....g++ tells me: "invalid use of non-lvalue array"
0
8310
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
8826
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
8732
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
8503
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
7330
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
6166
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
4155
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
4306
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2726
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

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.