|
-
September 7th, 2008, 04:13 AM
#1
[RESOLVED] Pointers in a Class
it doesn't shows the correct values
Code:
/*Triangle.hpp*/
#include <iostream>
using namespace std;
class Triangle
{
public:
Triangle();
~Triangle();
int GetSideC() const {return *itsSideC;}
int GetSideA() const {return *itsSideA;}
int GetSideB() const {return *itsSideB;}
void SetSideC(int c) {itsSideC = &c;}
void SetSideA(int a) {itsSideA = &a;}
void SetSideB(int b) {itsSideB = &b;}
private:
int *itsSideC;
int *itsSideA;
int *itsSideB;
};
Triangle::Triangle()
{
itsSideC = new int (0);
itsSideA = new int (0);
itsSideB = new int (0);
}
Triangle::~Triangle()
{
delete itsSideC;
delete itsSideA;
delete itsSideB;
}
/*myTriangle.cpp*/
#include "Triangle.hpp"
int main()
{
Triangle myTriangle;
myTriangle.SetSideC(5);
myTriangle.SetSideA(4);
myTriangle.SetSideB(3);
cout << "Triangle" << endl;
cout << "Side C:\t" << myTriangle.GetSideC() << endl;
cout << "Side A:\t" << myTriangle.GetSideA() << endl;
cout << "Side B:\t" << myTriangle.GetSideB() << endl;
cin.get();
return 0;
}
-
September 7th, 2008, 05:16 AM
#2
Re: Pointers in a Class
Why are you using int pointers in the first place, why not just an int ?
I believe the problem is that 'int a' is passed-by-copy, so when you do '&a', its a temp pointer you are using to store inside the class.
Code:
myTriangle.SetSideA(4);
void SetSideA(int a) {itsSideA = &a;}
Would advice you to change to
or atleast do
Code:
void SetSideA(int a) {*itsSideA = a;}
Before post, make an effort yourself, try googling or search here.
When posting, give a proper description of your problem, include code* and error messages.
*All code should include code tags
-
September 7th, 2008, 05:24 AM
#3
Re: Pointers in a Class
i used pointers because i'm studying in how to use them, anyway, thanks for the help!
Last edited by richard_tominez; September 7th, 2008 at 05:28 AM.
-
September 7th, 2008, 05:54 AM
#4
Re: Pointers in a Class
 Originally Posted by richard_tominez
i used pointers because i'm studying in how to use them, anyway, thanks for the help!
You don't study something by using it in ways that no programmer will use them.
And BTW, this program using your class has memory leaks and double deletion errors:
Code:
int main()
{
Triangle myTriangle;
myTriangle.SetSideC(5);
myTriangle.SetSideA(4);
myTriangle.SetSideB(3);
// add these three lines
Triangle tri2 = myTriangle;
Triangle tri3;
tri3 = myTriangle;
}
This code creates a memory leak, and possibly crashes your program on exit. Now to fix this, you will see why it would have been better to just use int instead of int pointers.
Regards,
Paul McKenzie
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|