-
overloading constructors
this is my program----------
Code:
#include <iostream>
#include <cstdlib>
class rectangle
{
public:
rectangle();
rectangle(int length, int width);
~rectangle() {}
int getlength() const {return itslength;}
int getwidth() const {return itswidth;}
private:
int itslength;
int itswidth;
};
rectangle::rectangle()
{
itswidth=10;
itslength=5;
}
rectangle::rectangle(int length, int width)
{
int itslength=length;
int itswidth=width;
}
int main()
{
rectangle rect1;
cout<<"rect1's length is "<<rect1.getlength()<<endl;
cout<<"rect1's width is "<<rect1.getwidth()<<endl;
int alength;
int awidth;
cout<<"\n\nNow enter a value for a new rectangle's length:";
cin>>alength;
cout<<"\nAnd now a value for its width:";
cin>>awidth;
rectangle rect2(alength, awidth);
cout<<"The new rectangle's values are:\n";
cout<<"length = "<<rect2.getlength()<<endl;
cout<<"width = "<<rect2.getwidth()<<endl;
system("PAUSE")
return 0;
}
the code compiles and all but whenever i display the values for the new rectangle, it doesnt work. like ill enter 5 and 5 for rect2, but itll display like 37365978 and 792654973. can anyone tell me why this/how to fix it?
-
Code:
rectangle::rectangle(int length, int width)
{
int itslength=length;
int itswidth=width;
}
You should not be declaring local variables itslength and itswidth. They end up hiding the member variables.
EDIT:
Actually, in this case it may be better to combine to a single constructor, and declare it inline. You dont need to explicitly declare a destructor.
Code:
class rectangle
{
public:
rectangle(int length = 10, int width = 5) : itslength(length), itswidth(width) {}
int getlength() const {return itslength;}
int getwidth() const {return itswidth;}
private:
int itslength;
int itswidth;
};
-
[QUOTE=chasingxsuns]this is my program----------
Code:
rectangle::rectangle(int length, int width)
{
int itslength=length; //you declared a new local variable
int itswidth=width; //the same here
}
The value it displayed seemed weird because that was garbage. You declared two new local variables whose names are the same as member variables of the class. So when the constructor is automatically called, the values will be passed to the local variables, not member variable as you expected.
You can modify your code by simply removing the "int" before itswidth and itslength, that tells the compiler that you're mutating the class member variables :
Code:
rectangle::rectangle(int length, int width)
{
itslength=length;
itswidth=width;
}