I honestly don't understand why C++ Does not recognise my parameter construction. It says there is an error in the object "rec" or "tri". When you look at the main code it says there is an error in the object rec(10,7) and tri (10,5). Why is it the case?
Please have a look below. Any help will be massively appreciated. I am still beginner in C++ so sorry for my basic questions. Thanks so much
#include <iostream>
using namespace std;
class Shape {
protected:
int width, height;
public:
Shape( int a=0, int b=0)
{
width = a;
height = b;
}
int area()
{
cout << "Parent class area :" <<endl;
return 0;
}
};
class Rectangle: public Shape{
public:
Rectangle( int a=0, int b=0):Shape(a, b) { }
int area ()
{
cout << "Rectangle class area :" <<endl;
return (width * height);
}
};
class Triangle: public Shape{
public:
Triangle( int a=0, int b=0):Shape(a, b) { }
int area ()
{
cout << "Triangle class area :" <<endl;
return (width * height / 2);
}
};
// Main function for the program
int main( )
{
Shape *shape;
Rectangle rec(10,7);
Triangle tri(10,5);
// store the address of Rectangle
shape = &rec;
// call rectangle area.
shape->area();
// store the address of Triangle
shape = &tri;
// call triangle area.
shape->area();
I don't get any errors but if you want the area() function to be called depend on what kind of object the shape pointer is pointing to you should make it a virtual function.
Thank you for your reply. The code is taken from a C++ tutorial website so I am not surprised that it works on your end. I just dont understand why my C++ (version 2010) says there is mistake in rec(10,7) or tri(10,5)??
Sadly all our telepath's are currently on vacation and we are not able to get exact error message you are getting. You can post it yourself to decrease waiting time.