How to resolve not a member of base class when create derived object using new operator
When i execute the below program, i am getting the below error only when i create a object using new operator "shape *s=new Rectangle";. But i havent faced any issues when i create object "Rectangle s"
Actually i dont want to use hello method in my Triangle class. Need to acces/uses hello method in rectangle class by creating object using new operator "shape *s=new Rectangle".
Please let us know how to resolve this issue using new operator.
Error:
1>c:\shape\shape\shape.cpp(60) : error C2039: 'hello' : is not a member of 'Shape'
1>c:\shape\shape\shape.cpp(10) : see declaration of 'Shape'
Code snippet:
// Shape.cpp : Defines the entry point for the console application.
//
#include <iostream>
using namespace std;
// Base class
class Shape
{
public:
// pure virtual function providing interface framework.
virtual int getArea() = 0;
void setWidth(int w)
{
width = w;
}
void setHeight(int h)
{
height = h;
}
protected:
int width;
int height;
};
// Derived classes
class Rectangle: public Shape
{
public:
int getArea()
{
return (width * height);
}
void hello()
{
std:cout<<std::endl<<"hello"<<std::endl;
}
};
class Triangle: public Shape
{
public:
int getArea()
{
return (width * height)/2;
}
};
int main(void)
{
Shape *s= new Rectangle;
// Triangle Tri;
s->setWidth(5);
s->setHeight(7);
// Print the area of the object.
cout << "Total Rectangle area: " << s->getArea() << endl;
s->hello();
/*
Tri.setWidth(5);
Tri.setHeight(7);
// Print the area of the object.
cout << "Total Triangle area: " << Tri.getArea() << endl;
*/
return 0;
}