Code is compiling but its not giving correct volume - c++

How to correct this code, its not working properly.
length and width is not getting the correct values.
I'm having problem where I declared Rectangle::get().
#include<iostream>
using namespace std;
class Rectangle{
protected:
double length;
double width;
public:
void setter(double len, double wid)
{
length = len;
width = wid;
}
double get()
{
return length*width;
}
};
class Block: public Rectangle{
private:
double heigth;
public:
void setter_h(double hei)
{
heigth = hei;
}
double get_1()
{
return(heigth * Rectangle::get());//this is the problem
}
};
int main()
{
double len, hei, wid;
cout<<"Enter the length: ";
cin>>len;
cout<<"Enter the Width: ";
cin>>wid;
cout<<"Enter the H: ";
cin>>hei;
Rectangle R1;
R1.setter(len,wid);
cout<<"Area: " << R1.get();
Block B1;
B1.setter_h(hei);
cout<<"Volume: "<< B1.get_1();
}
Can someone please help me???
im totaly confused because i think i have written right code but its giving garbage value for volume.

Because you didn't set the width and length for B1. You should also call
B1.setter(len, wid);
before calling B1.get_1().

Related

Why it keeps return 0 when I enter the Data of The Heigh & Base

class BASIC_SHAPE (abstract)
class BASIC_SHAPE
{
public:
double GET_AREA(double _AREA) { AREA = _AREA; return AREA; }
virtual double CALC_AREA() = 0;
private:
double AREA =0;
};
Class CIRCLE
class CIRCLE:public BASIC_SHAPE
{
public:
CIRCLE() { RADIUS = 0; }
CIRCLE(double _RADIUS) { RADIUS = _RADIUS; }
virtual double CALC_AREA() {
double TEMP2 = 3.14 * pow(RADIUS, 2);
return GET_AREA(TEMP2);
}
private:
double RADIUS;
};
Class TRIANGLE
class TRIANGLE: BASIC_SHAPE
{
public:
TRIANGLE() { BASE = 0; HEIGHT = 0; }
TRIANGLE(double _BASE , double _HEIGHT) : BASE{_BASE}, HEIGHT{_HEIGHT} {}
virtual double CALC_AREA() {
double TEMP = 1 / 2 * (BASE * HEIGHT);
return GET_AREA(TEMP);
}
private:
double BASE, HEIGHT;
MAIN
CIRCLE SHAPE2;
TRIANGLE SHAPE3;
void main()
{
double RAD;
std::cout << "Enter a Circle Radius : ";
std::cin >> RAD;
CIRCLE SHAPE2(RAD);
CIRCLE* LEAD1 = new CIRCLE(RAD);
std::cout << "The Area is : " << LEAD1->CALC_AREA();
double BASE , HEIGHT;
std::cout << "\n\nEnter a Triangle Base : ";
std::cin >> BASE;
std::cout << "\nEnter a Triangle Height : ";
std::cin >> HEIGHT;
TRIANGLE SHAPE3(BASE, HEIGHT);
std::cout << SHAPE3.CALC_AREA();
}
it keeps returning zero when I input the BASE & HEIGHT
I have tried using arrow operator and get it with pointers put nothing worked , I,ve tried use pointers and other methods to give me the answer or the SUM of area but nothing happens . constructors or abstract Class are suspected but IDK how ??
As pointed out in the comments by #rturrado 1/2 is 0. 0 times anything is 0. either use 0.5 or 1/2.0*....
Also, why does your GET_AREA method set the area for the base class and return the set area? You need to have different getters and setters. Getter methods should not set and similarly setter methods should not get.
Also, it would be best if you get in the habit of using managed pointers.

Deleting a pointer from a vector... Error: terminate called after throwing an instance of 'std::bad_alloc' what(): std::bad_alloc

I'm getting the error after I delete a pointer from the vector and try to delete a second one. I'm still new to pointers
I created a base class of shapes and have multiple shapes derived classes not shown here and I have to store them in a vector of pointers.
I ask the user to add shapes of their choice measures and calculate the volumes
then I also ask what shapes they want to remove.
#include <string>
#include <iostream>
#include <vector>
#include <iomanip>
#define _USE_MATH_DEFINES
#include <cmath>
using namespace std;
class Luggage {
private:
static double totalVolume;
protected:
string type;
static int count;
static int serialGen;
int serialNum;
public:
Luggage() {
type = "Luggage";
count++;
serialNum = serialGen++;
cout<<"Generating Luggage"<<getSN()<<endl;
}
// 'static' can only be specified in the class header file not source
void static updateVolume(double inVolume) {
totalVolume += inVolume;
}
virtual
~Luggage() {
cout<<"Luggage Destructor"<<getSN()<<endl;
count--;
}
static int getCount() {
return count;
}
string getType() {
return type;
}
string getSN() {
return "(SN: " + to_string(serialNum) + ")";
}
virtual double getVolume()=0;
static double getLuggageVolume() {
return totalVolume;
};
friend ostream & operator<<(ostream & out, Luggage * lptr) {
out<<setw(10)<<left<<lptr->getType()<<": "
<<setw(6)<<right<<setprecision(1)
<<fixed<<lptr->getVolume()<<" ~ "<<lptr->getSN();
return out;
}
};
class Box : public Luggage {
private:
double length, width, height;
static int count;
static double totalVolume;
public:
Box(double l, double w, double h){
count++;
type = "Box";
length = l;
width = w;
height = h;
cout<<"Generating a Box with a Volume: "<<getVolume()<<getSN()<<endl;
updateVolume(getVolume());
}
~Box() {
count--;
updateVolume(getVolume() * -1);
cout<<"Destroying a Box with Volume: "<<getVolume()<<getSN()<<endl;
}
double getVolume() {
return length*width*height;
}
static int getCount() {
return count;
}
static double getTotalVolume() {
return totalVolume;
}
};
int main() {
// Your main program will create a container of luggage and be able to add luggage items
// and remove them as well. This container will be a vector of luggage pointers.
vector<Luggage*> container;
int input; // Main Menu User input
bool io = true;
while(io){
// Main Menu
cout << "\n----Main Menu----\n"
"1) Add Luggage to storage container\n"
"2) Remove Luggage from storage container\n"
"3) Show all luggage\n"
"4) Show total volumes\n"
"5) Exit\n\n"
"Enter: ";
Luggage *lptr;
cin >> input;
if(input == 1){
int shapeChoice;
cout<<"\nWhat Shape do you want? "<<endl
<<"1) Box"<<endl
<<"2) Cube"<<endl
<<"3) Cylinder"<<endl
<<"4) Pyramid"<<endl
<<"5) Sphere"<<endl;
cin>>shapeChoice;
switch (shapeChoice){
case 1: { // Box
double length, width, height;
cout << "\nEnter length of Box: ";
cin >> length;
cout << "Enter width of Box: ";
cin >> width;
cout << "Enter height of Box: ";
cin >> height;
lptr = new Box(length, width, height);
container.push_back(lptr);
break;
}
default:
cout << "Bad choice! Please try again later.\n";
break;
}
}else if(input == 2) {
int count = 0;
for(auto l:container) // container is vector<Luggage*>
cout << ++count << ") "<< l << endl;
cout<<"What element do you want to remove? "<<endl;
int removeChoice;
cin>>removeChoice;
removeChoice-=1;
delete (lptr);
container.erase(container.begin()+removeChoice);
}
}
delete (lptr);
This statement is wrong.
lptr is pointing at the last Box object pushed into the vector. If nothing was pushed yet, this statement causes undefined behavior since lptr is uninitialized before the 1st push. Otherwise, you are destroying the last object pushed, and then you are left with a dangling pointer, which will then fail on the next delete, causing undefined behavior again, unlese you push a new object that updates lptr beforehand.
That statement should be this instead:
delete container[removeChoice];
or safer:
delete container.at(removeChoice);
since you are not validating removeChoice beforehand.
But either way, you really shouldn't new/delete objects manually in modern C++. Use smart pointers instead, in this case std::unique_ptr<Luggage>, and let it deal with destroying objects for you.

Having Trouble with Inheritance in C++

I'm having a little trouble with inheritance.
Main.cpp
#include <iostream>
#include "Shapeclass.h"
using namespace std;
int main() {
int shapecount, shapetype[200],i,height[200], width[200];
string name;
cout << "AREA CALULATOR";
cout << "Enter Your Name ";
cin >> name;
cout << "Enter the amount of Shapes you want to calculate Area of: ";
cin >> shapecount;
Shape *p1[200];
cout << "Enter 1 for Circle Enter 2 for Rectangle and 3 for Triangle";
for ( i = 0; i < shapecount; i++)
{
cin >> shapetype[i];
}
for ( i = 0; i < shapecount; i++)
{
if (shapetype[i]==1)
{
cout << "Enter Radius of circle";
cin >> width[i];
p1[i] = new sphere(width[i]);
}
else if (shapetype[i] == 2) {
cout << "Enter width of rectangle";
cin >> width[i];
cout << "Enter height of rectangle";
cin >> height[i];
}
else if (shapetype[i] == 3) {
cout << "Enter base of triangle";
cin >> width[i];
cout << "Enter height of triangle";
cin >> height[i];
}
}
}
Shapeclass.h
#include <iostream>
using namespace std;
class Shape
{
protected:
double area ;
int height, width;
string nama;
void virtual calculate() = 0;
public:
void display() {
calculate();
}
private:
};
class sphere :public Shape {
void calculate(double height, double width) {
}
};
class rectangle :public Shape {
public:
rectangle(int width1, int height1)
{
width = width1;
height = height1;
}
void calculate(double height, double width) {
area = height * width;
}
};
class triangle :public Shape {
public:
triangle(int width1, int height1)
{
width = width1;
height = height1;
}
void calculate(double height, double width) {
area = height * width*0.5;
}
};
class sphere :public Shape {
public:
sphere(int width1)
{
width = width1;
}
void calculate(double width) {
area = width*width*3.14 ;
}
};
I have no idea why it says object of abstract class type "sphere" is not allowed. Specifically line 42.
I'm trying to initialize pointer array objects but it doesn't want to work.
I'm trying to send the width of the sphere to the class but I can't initialize the value of width with the pointer array. To be more specific.
The Shape::calculate() method is declared as pure virtual:
void virtual calculate() = 0;
So, it must be overloaded in derived classes to have them considered by the compiler as concrete ones you'd able to call.
In your case, the overloaded method would be responsible to determine the area of each shape according to its kind and update the instance property.
for example:
void rectangle::calculate() {
area = height * width;
}
and
void triangle::calculate() {
area = height * width * 0.5;
}
would compute the right area for given shapes.
Shape* s1 = new triangle(w, h);
s1->calculate(); // effective call to triangle::calculate()
Shape* s2 = new rectangle(w, h);
s2->calculate(); // effective call to rectangle::calculate()

I am getting an error in typecasting, please help me out with this

Create a class Rectangle. This class has attributes length and width each of which defaults to 1. It has methods that calculate the perimeter and area of the rectangle. It has set and get methods for both length and width. The set methods should verify that length and width are floating – point nos larger than 0.0 and less than 20.0.
#include<iostream>
using namespace std;
class rect
{
float l;
float w;
public:
void setlw();
float getl(float len);
float getw(float width);
void seta();
void setp();
};
void rect:: setlw()
{
cout<<"enter the lenght and width"<<endl;
cin>>l>>w;
}
float rect:: getl(float len)
{
if (l>=0.0 && l<=20.0)
len=l;
else
len=1.0;
return(len);
}
float rect:: getw(float width)
{
if(w>=0 && w<=20.0)
width=w;
else
width=1.0;
return(width);
}
void rect::seta()
{
float a;
a=l*w;
cout<<"the area is"<<a<<endl;
}
void rect:: setp()
{
float p;
p=2*(l+w);
cout<<"the perimeter is"<<p<<endl;
}
int main()
{
rect r;
r.setlw();
cout<<"length is"<<r.getl(float)<<endl;
cout<<"width is"<<r.getw(float)<<endl;
r.seta();
r.setp();
return (0);
}
I have corrected your code. Removed the input parameters for getl() and getw(), as it's not required when you are taking input with setlw() . You've also not declared variables len and width in functions getl and getw.
New Code:
#include<iostream>
using namespace std;
class rect
{
float l;
float w;
public:
void setlw();
float getl();
float getw();
void seta();
void setp();
};
void rect::setlw()
{
cout<<"enter the lenght and width"<<endl;
cin>>l>>w;
}
float rect::getl()
{ float len;
if (l>=0.0 && l<=20.0)
len=l;
else
len=1.0;
return(len);
}
float rect::getw()
{ float width;
if(w>=0 && w<=20.0)
width=w;
else
width=1.0;
return(width);
}
void rect::seta()
{
float a;
a=l*w;
cout<<"the area is"<<a<<endl;
}
void rect::setp()
{
float p;
p=2*(l+w);
cout<<"the perimeter is"<<p<<endl;
}
int main()
{
rect r;
r.setlw();
cout<<"length is"<<r.getl()<<endl;
cout<<"width is"<<r.getw()<<endl;
r.seta();
r.setp();
return (0);
}

Using header file in C++ program

I have some question for coding C++ program with header file.
This is my header.h file :
#include <iostream>
using namespace std;
class Rectangle
{
public:
Rectangle(double width, double length);
double get_perimeter();
double get_area();
void resize(double factor);
private:
double width;
double length;
double area;
double factor;
};
And this is my Question1.cpp file which store all the methods:
#include <iostream>
using namespace std;
class Rectangle
{
public:
Rectangle(double width, double length)
{
width = width; //I have no idea how to use this.something as its in Java
length = length; //Problem probably occurs at here
}
double Rectangle::get_perimeter()
{
return ((width * 2) + (length * 2)) ;
}
double Rectangle::get_area()
{
return (width * length);
}
void Rectangle::resize(double factor)
{
width *= factor;
length *= factor;
}
private:
double width;
double length;
double area;
double factor;
};
And lastly, here is my main method.cpp :
#include <iostream>
#include "header.h";
using namespace std;
int main()
{
Rectangle rectangle1(2.5,7.0);
cout << rectangle1.get_perimeter();
cout << rectangle1.get_area();
system("PAUSE");
return 0;
}
However, when I try to run the program, the system told me that there was build errors and unresolved externals which I have no idea why is it so. Could somebody please help me fix it?
Thanks in advance.
Your implementations should not look like
class Rectangle
{
public:
Rectangle(double width, double length) { .... }
but like
Rectangle::Rectangle(double width, double length) : width(width), length(length) {}
You need to include header.h in the implementation .cpp file and in any file that needs the definition of the Rectangle class. You also need include guards in your headers. And do not put using namespace std in a header. In fact, don't put it anywhere.
Change .h to ->
#include <iostream>
using namespace std;
class Rectangle
{
public:
Rectangle(double width, double length);
double get_perimeter();
double get_area();
void resize(double factor);
private:
double width;
double length;
double area;
double factor;
};
Then .cpp to->
#include <iostream>
#include "header.h"
using namespace std;
Rectangle::Rectangle(double width, double length)
{
this->width = width; //I have no idea how to use this.something as its in Java
this->length = length; //Problem probably occurs at here
}
double Rectangle::get_perimeter()
{
return ((this->width * 2) + (this->length * 2)) ;
}
double Rectangle::get_area()
{
return (this->width * this->length);
}
void Rectangle::resize(double factor)
{
this->width *= factor;
this->length *= factor;
}
This should work then.
Regards,
Luka
Few things to unpick here.
1) use this->width which is equivalent to java's this.width (In C++, this is a pointer). Actually some C++ programmers (including me) prefix member variables with m_. Then you can just write m_width = width.
2) include "header.h" at the top of Question1.cpp
3) avoid putting "using namespace std" in a header file, or you could get unintended namespace
clashes as your code expands. OK to put it in the separate source files though although some folk even discourage this.
4) depending on your compiler and linker, you'll need to link to various lib's that the iostream library uses. Perhaps if you tell us the compiler you're using, we can help you here.
5) you need to surround your header with
#ifndef ARBITRARY_TEXT_BUT_DISTINCT_FROM_ANY_OTHER_IN_YOUR_PROGRAM
#define ARBITRARY_TEXT_BUT_DISTINCT_FROM_ANY_OTHER_IN_YOUR_PROGRAM
...your code here
#endif
This is an include guard - helps prevent multiple inclusion of a header file contents.
In Question1.cpp you have to include header.h
And don't forget include guards in header.h
Also in Question1.cpp you must change
Rectangle(double width, double length)
to
Rectangle::Rectangle(double width, double length)
You need to tell your build system to compile "question1.cpp". Usually there is an "add existing file to project" menu item somewhere under "File".
And typically, your class and constructor would use a different name than the input parameter. Many people put a prefix at the begginning (mLength, iLength) or postfix at the end (length_ is common).
The other solution is to prefix the member variable with this->length, but that can get pretty messy after a while.
the big mistake that in the .cpp file you are supposed to implement only the methods not rewrite full class implementation try the following in .cpp file
Rectangle::Rectangle(double width, double length)
{
width = width; //I have no idea how to use this.something as its in Java
length = length; //Problem probably occurs at here
}
and don't include the methods in class{}; block and don't redefine your member variables
also don't forget to include the header file in the .cpp file
thanks
I wonder if you are getting linker errors as your cpp file is little weird
In the cpp file include the .h file and only implement the functions like
Rectangle::Rectangle(double width, double length){
//implement
}
double Rectangle::get_perimeter(){
//implement
}
double Rectangle::get_area(){
//implement
}
void Rectangle::resize(double factor){
//implement
}
When you want to split your class file into a *.cpp and a *.h file it always has the following form:
rectangle.h:
#ifndef __RECTANGLE_H_
#define __RECTANGLE_H_
#include <iostream>
using namespace std;
class Rectangle
{
public:
Rectangle(double width, double length);
double get_perimeter();
double get_area();
void resize(double factor);
private:
double width;
double length;
double area;
double factor;
};
#endif
now the rectangle.cpp should have the following form:
#include <iostream>
#include "rectangle.h"
using namespace std;
Rectangle(double width, double length)
{
width = width; //I have no idea how to use this.something as its in Java
length = length; //Problem probably occurs at here
}
double Rectangle::get_perimeter()
{
return ((width * 2) + (length * 2)) ;
}
double Rectangle::get_area()
{
return (width * length);
}
void Rectangle::resize(double factor)
{
width *= factor;
length *= factor;
}
so when as an explanation:
The header file tells you which fields and methods are available and the *.cpp file implements the methods.
In your main.cpp you just need o include the rectangle.h
this code below works
#include<iostream>
#include<iomanip>
using namespace std;
class student
{
private:
int area;//hours;
float perimeter;//gpa;
public:
void addcourse(int len, float wid)
{
float sum;
sum = area * perimeter;
area += len;
sum += wid * len;
perimeter = sum / area;
}
student() // constructor
{
area = 0;
perimeter= 0.0;
}
};
int main()
{
student s;
int length;//classhours;//l
float width;//classgpa;//w
cout << "Enter length ( 1 to end): ";
cin >> length;
while(length != 1)
{
cout << "Enter width: ";
cin >> width;
s.addcourse(length, width);
cout << "Enter length ( 1 to end): ";
cin >> length;
}
// cout << "Rectangle's length = " << r.getlength() << endl;
// cout << "Rectangle's width = " << r.getwidth() << endl;
// cout << "Rectangle's area = " << r.getarea() << endl;
// cout << "Rectangle's perimeter = " << r.getperimeter() << endl;
}