The simplest fix is to initialize the variable instead of declare-then-assign.
#include <iostream>
using namespace std;
class rectangle
{
private:
int *width,*length;
public:
rectangle(int width,int length)
{
this->length=new int(length); // Initialize with value
this->width=new int(width);
// *width=width;
// *length=length;
}
void print()
{
cout<<*width * *length;
}
};
int main()
{
rectangle *r1;
r1=new rectangle(5,6);
r1->print();
delete r1;
return 0;
}
A big issue with your code as-is is that you violate the Rule of 5. Most notably in your case, you didn't create a destructor, and your rectangle class leaks memory. Deleting the rectangle pointer does not delete the memory that was allocated by the class itself.
Since you don't demonstrate any real reason to allocate those integers, it will be easier to just not. Then you don't have to worry about a destructor.
Some suggestions for better code are below.
#include <iostream>
// using namespace std; // CHANGE: Bad practice
// CHANGE: Class names start with uppercase letter
class Rectangle {
private:
int width = 0; // CHANGE: No pointers, default member initialization
int length = 0;
public:
Rectangle(int width, int length) : width(width), length(length) {
// CHANGE: Use ctor initialization section; body no longer needed
//
// this->length=new int(length); // Initialize with value
// this->width=new int(width);
// *width=width;
// *length=length;
}
// CHANGE: Replace print() with operator<<()
friend std::ostream& operator<<(std::ostream& sout, const Rectangle& rect) {
return sout << rect.width * rect.length;
}
// void print()
// {
// cout<<*width * *length;
// }
};
int main() {
Rectangle r1{5, 6}; // CHANGE: No demonstrated need to 'new' a rectangle;
// initialize > declare/assign
std::cout << r1 << '\n'; // CHANGE: Can now std::cout directly
// delete r1;
return 0;
}
Finally, here is the code above, with all comments removed. I know sometimes this helps with read-ability when there's a mix of old/new code. It also, to me, highlights how much cleaner some of the new practices can be when you can format without worrying about keeping dead code.
#include <iostream>
class Rectangle {
private:
int width = 0;
int length = 0;
public:
Rectangle(int width, int length) : width(width), length(length) {}
friend std::ostream& operator<<(std::ostream& sout, const Rectangle& rect) {
return sout << rect.width * rect.length;
}
};
int main() {
Rectangle r1{5, 6};
std::cout << r1 << '\n';
return 0;
}