How do abstract classes work in c++?

Started by
3 comments, last by Zahlman 17 years, 8 months ago
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.
Advertisement
It should work, assuming you have not forgotten the ; after your class definitions, and that you remember to provide a virtual destructor.
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan
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;}
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.
Note also that you probably shouldn't actually be deriving Circle from Ellipse (although the above general principles stand, and you do need this kind of inheritance sometimes).

This topic is closed to new replies.

Advertisement