Reputation: 23
hello :) so this is my first time writing a c++ program, im currently using code::blocks tho im pretty sure the issue ive got probably isnt related to the program at all but anyway...
i want to write a simple code, where two "boxes" are created and their volume is calculated and printed on the terminal. ive written this code on a single cpp file:
#include<iostream>
using namespace std;
class Box
{
public:
double length;
double breadth;
double height;
Box(double l, double b, double h)
{
l=length;
b=breadth;
h=height;
}
};
int main()
{
double volume = 0.0;
Box BoxA(2.0, 3.2, 6.0);
Box BoxB(2.5, 4.0, 5.0);
volume = BoxA.length * BoxA.breadth * BoxA.height;
cout << "Box a volume = " << volume <<endl;
volume = BoxB.length * BoxB.breadth * BoxB.height;
cout << "Box b volume = " << volume <<endl;
return 0;
}
so i build and run this thing, no errors but the results i get is this:
box a volume = -0
//and sometimes =0
box b volume = 0
but i dont understand what is wrong here. shouldnt the results be a=38.4 and b=50.0? what am i doing wrong here?
Upvotes: 1
Views: 101
Reputation: 4382
Your constructor assigns values to the passed arguments.
Try this instead:
class Box
{
public:
double length;
double breadth;
double height;
Box(double l, double b, double h)
{
length=l;
breadth=b;
height=h;
}
};
As others have mentioned, there are other improvements that can be made regarding initializer lists and the use of using
, and the study of programming in general and c++ in particular is an ongoing journey, never a destination, but this is the direct fix for the immediate problem.
Upvotes: 3
Reputation: 179799
The usual way to write constructors is with initializer lists:
Box(double l, double b, double h) : length(l), breadth(b), height(h)
{
}
This prevent exactly the same error that you had, exchanging the argument and member. If you tried to write : l(length),
the compiler would have told you straight away that l
is not a member of Box
.
You don't even need separate names with initializer lists:
Box(double length, double breadth, double height)
: length(length), breadth(breadth), height(height)
{ }
This does initialize Box::height
with the argument height
.
Upvotes: 3
Reputation: 7726
#include<iostream>
class Box
{
public:
double length;
double breadth;
double height;
Box(double l, double b, double h)
{
length = l; // assign to the member variables, not parameters
breadth = b;
height = h;
}
};
int main(void)
{
double volume = 0.0;
Box BoxA(2.0, 3.2, 6.0);
Box BoxB(2.5, 4.0, 5.0);
volume = BoxA.length * BoxA.breadth * BoxA.height;
std::cout << "Box a volume = " << volume << std::endl;
volume = BoxB.length * BoxB.breadth * BoxB.height;
std::cout << "Box b volume = " << volume << std::endl;
return 0;
}
This is the refined version of your code. Note that you shouldn't use namespace std. That's a bad programming practice.
Upvotes: 2