简体   繁体   中英

How do I access member functions of concrete class when I'm using Polymorphism and inheritance to declare it as a pointer to the concrete class

Say I have an abstract class.

class shape{
public:
shape();
double getWidth();

private:
float m_center;
};

and I have a class that inherits from shape.

class triangle : public shape{
public:
triangle(vector<double> a, vector<double> b, vector<double> c);
vector<double> getPoints();
void setPoints();
private:
double pointA, pointB, pointC;
};

Then say my code is formatted so that when I dealing with shapes I get the shape data in the form of shape pointers. However there are times when I need to access the member functions of the Triangle class, but I only have the shape*

int main(){
shape* generalShape = new triangle()     
std::cout << generalShape -> getWidth() << std::endl;

std::vector<double> tempVector = generalShape -> getPoints();    //<- can't do this part.

So I can't call member functions from the shape* object so I was just wondering if there is a way to do this or if I have my code structured completely wrong.

Assuming it doesn't make sense to use a virtual function in the base class, you can achieve this doing a dynamic_cast. There does need to be at least one virtual function in base class.

triangle* newPtr = dynamic_cast<triangle*>(generalShape);

One should understand the costs and advantages of this approach (run-time polymorphism); and consider whether it is more efficient to redesign the class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM