//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){;}