Hey guys, I'm practising using the this pointer and trying to make a member function const at the same time.
header file:
definition file:
test file:
This code works perfectly but when i try to make a member function const like getwidth() for example, the compiler returns an error: 1>z:\college\year2\semester 2\programming\assignment 2 rectangle\assignment 2 rectangle\rectangle definition.cpp(34) : error C2440: 'return' : cannot convert from 'const rectangle' to 'rectangle &'
Is it not possible to do this at all?
header file:
Rich (BB code):
#ifndef rectangle_h
#define rectangle_h
class rectangle
{
public:
rectangle(double = 0,double = 0, double = 0);
rectangle & setlength();
rectangle & setwidth();
rectangle & getlength();
rectangle & getwidth();
rectangle & calculateArea();
rectangle & displayArea();
private:
double area, length, width;
};
#endif
Rich (BB code):
#include "Rectangle.h"
#include <iostream>
using namespace std;
rectangle::rectangle(double Area, double Length, double Width)
{
area = Area;
length = Length;
width = Width;
}
rectangle &rectangle::calculateArea()
{
area = length*width;
return *this;
}
rectangle &rectangle::displayArea()
{
cout << "The area of rectangle with length " << length << " and width " << width << " is " << area << endl;
return *this;
}
rectangle &rectangle::getlength()
{
cout << "The length of the rectangle is " << length << endl;
return *this;
}
rectangle &rectangle::getwidth()
{
cout << "The width of the rectangle is " << width << endl;
return *this;
}
Rich (BB code):
#include "Rectangle.h"
#include <iostream>
using namespace std;
int main()
{
rectangle rectangle1(1,1,1); //create object with area, width and length of 1
rectangle1.getlength().getwidth().displayArea();
rectangle rectangle2;
rectangle2.getlength().getwidth().displayArea();
rectangle2 = rectangle1;
cout << "After using a copy contructor\n";
rectangle2.getlength().getwidth().displayArea();
return 0;
}
This code works perfectly but when i try to make a member function const like getwidth() for example, the compiler returns an error: 1>z:\college\year2\semester 2\programming\assignment 2 rectangle\assignment 2 rectangle\rectangle definition.cpp(34) : error C2440: 'return' : cannot convert from 'const rectangle' to 'rectangle &'
Is it not possible to do this at all?