A short question on Pointers as members

Hello,

here's my next question.... (and it isn't about semicolons).
Is it possible to define a class with pointers as members and a constructor called with identifiers ??.... for example
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class zwei{

   double *a;
   double *b;

public:
//Constructor
   zwei(double, double);
   //zwei();
   
   double geta(){return *a;};
   double getb(){return *b;};
   ~zwei();
   zwei operator+ (zwei);
};


and a constructor looking like

1
2
3
4
5
zwei::zwei(double x, double y){
			a=&x; 
			b=&y;
}


In my example the call of the constructor overwrites the values of the members of the Object defined before..... i.e.
1
2
3
4
5
6
7
8
9

int main(){double s = 1.5; 
           double d=2; 
	    zwei ar(s, d);

           double g=3; 
           double m=4;
	    zwei br(g,m);
//..............t.b.c. ..... 

always results in identical objects. So far i think i figured out why this occurs, but is it possible to solve this ?
I mean to keep the members as pointers but call the constructor with double arguments (??)
And (this might be a little late) ... would this be useful for something ?

Thanks so far....
And (this might be a little late) ... would this be useful for something ?

No, not really. Why would you want to keep them as a pointer?

1
2
a=&x; 
b=&y;

doesn't work because x and y are local objects and are destroyed when the function exits.
However, you could use dynamic allocation if you really wanted to.
In this definition of the constructor

1
2
3
4
zwei::zwei(double x, double y){
			a=&x; 
			b=&y;
}


x and y are local variables that will be destroyed after exiting the constructor. So the behaviour of such code is undefined.
It would be better to define the consttructor the following way

1
2
3
4
zwei::zwei(double *x, double *y){
			a=x; 
			b=y;
}


However even in this case it is a bad design. An object of the class can live longer then objects pointers to which the class object stores. Consider the following example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
double x1 = 1.0;
double y1 = 1.0;
zwei z1( &x1, &y1 );

int main()
{
   {
      double x2 = 2.0;
      double y2 = 2.0;
      zwei z2( &x2, &y2 );
      z1 = z2;
   }
   //Where do z1.a and z1.b point now? x2 and y2 were already destroyed

   return 0;
}
Last edited on
1
2
3
4
5
6
7
8
9
10
zwei::zwei(double x, double y){
			a= new double(x); 
			b= new double(y);
}


zwei::~zwei(){
   delete a;
   delete b;
}
@clanmjc


You need also to define a copy constructor and the copy assignment operator.
Yes he would need to. I just did minimal copy and paste before I got my cup of Joe.
Well, that was a lot.....

@clanmjc & vlad: I'm going to look up those "copy" operators.... Until then i will simply not use a constructor like the one in my example. .......
@Athar: I believe this....

Thanks a lot for your response.

Topic archived. No new replies allowed.