Need help with pointers

I don't get why the address of 'a' and value of 'first.mLength' are different. Shouldn't they be equal from the way the class Rect is constructoed?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
//Keyword new examples
//Copy constructor examples
#include <iostream>

class Rect//Contains definition of the class Rect
{
public://Contains functions with public access
    double * mLength, * mWidth;//Pointers to the Length and Width of the Rect object
public://Contains functions with public access
    Rect(double l, double w):mLength(&l),mWidth(&w){;}//Constructor using member initialization
};

int main()//Definition of the main function
{
    double a=3.0, b=4.0;
    Rect first(a,b);//Creating a Rect object
    std::cout<<"Address of a :"<<&a<<" and value of member mLength of Rect :"<<first.mLength<<"\n";//Print out stuff
    return 0;//Program returns 0 if successful
}
The problem is that when you pass in the doubles a and b into the constructor, it copies those values (not the addresses themselves!) into new memory addresses.
mLength is then being assigned this unrelated address of the l variable.

If you pass them by reference this won't happen
Rect(double& l, double& w):mLength(&l),mWidth(&w){;}
Last edited on
I get it now. Thanks.
Topic archived. No new replies allowed.