• Advertisement
Sign in to follow this  

How do abstract classes work in c++?

This topic is 4225 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hello, I'm a bit confused about c++ and pure virtual methods. What I is to have a base class, say Shape which can not be instantiated but which will require some method from an implementing class: class Shape { virtual void getArea() = 0; } And then an implementing class would need to define the method: class Elipse : public Shape { virtual void getArea() { return 40; } } This is fine, but when a class inherits Elipse, I don't want it to have to define getArea as it's been defined in Elipse, but trying: class Circle : public Elipse {} main() { Circle circle; } Does not compile because Shape::getArea is pure virtual. Why is this? What should I do to obtain the behaviour I want (An interface class defining the methods required and any implementation using the "closest" method)? I think I expected this to work because Interfaces in Java work like this? Any help would be wonderfull.

Share this post


Link to post
Share on other sites
Advertisement
It should work, assuming you have not forgotten the ; after your class definitions, and that you remember to provide a virtual destructor.

Share this post


Link to post
Share on other sites
If I change your function to return a float instead of void, and put semicolons after the class definition, it compiles just fine.


class Shape
{
virtual float getArea() = 0;
};

class Elipse : public Shape
{
virtual float getArea() { return 40; }
};

class Circle : public Elipse
{};

main()
{
Circle circle;
}

Share this post


Link to post
Share on other sites
Arr okay. That's embarrasing. So either I have weird compiler options in my project or I completely misunderstood the compiler errors. I'll look it over. Thank you.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement