I am doing an exercise in which I create a class Color which contains three attributes, red, green, and blue which are pointers to ints.
Initially, I did my constructor as follows.
class Color{
int* red;
int* green;
int* blue;
public:
//getters
int getRed()const{return *red;}
int getGreen()const{return *green;}
int getBlue()const{return *blue;}
//constructor
Color(int Red, int Green, int Blue): red(&Red), green(&Green), blue(&Blue){
cout<<"Regular constructor called."<<endl;
}
//copy constructor
Color(const Color& c){
}
};
int main(){
Color buddy=Color(1,2,3);
cout<<"The color's name is buddy. red: "<<buddy.getRed()<<". green: "<<buddy.getGreen()<<". blue: "<<buddy.getBlue()<<endl;
cout<<"buddy red before copy constructor called: "<<buddy.getRed()<<endl;
Color holly(buddy);
// Color *geonwoo=erin;
cout<<"buddy red after copy constructor called: "<<buddy.getRed()<<endl;
return 0;
}
This gave an output of:
Regular constructor called. The color's name is buddy. red: 1. green: 2. blue: 3 buddy red before copy constructor called: 1 buddy red after copy constructor called: -249563152
(I'm aware the copy constructor isn't doing anything, I'm just calling it to demonstrate what's happening to the object passed in).
When I changed the constructor to this:
Color(int Red, int Green, int Blue){
this->red=new int(Red);
this->green=new int(Green);
this->blue=new int(Blue);
}
I got the desired result. Can anyone tell me why this is? I don't feel I'm fully understanding what's happening.