bingo157
bingo157

Reputation: 153

c++ - inheritance- the same method name in two different classes

I'm new in C++ and I have maybe easy for you question.

class circle {
  protected:
     int r;
  public:
     circle(int re) { r=re; }

     double surface() {
        return 3.14*r*r;
     }
 };

 class sphere : public circle {
    public:
      sphere(int r) : circle(r) {}
      double surface(){
        return 4*3.14*r*r;
      }
 };

And now, my problem is how I can do something like that: create a sphere object and using it to get surface not of a sphere but of a circle. Can I use somehow the same methods names in two classes, when one is inherited by the second one?

Upvotes: 0

Views: 4306

Answers (2)

user2030052
user2030052

Reputation:

Your design is initially wrong. Public inheritance in C++ means that the child is-a specific kind of the parent. A sphere is not a circle!

Besides, if you do want to get the surface area of the sphere, you should make your surface function virtual:

class Circle {
    public:
    virtual double surface();
};

That way, when you override it in Sphere, the Sphere version will be called.

Upvotes: 3

rems4e
rems4e

Reputation: 3172

You can have access to the base class' surface method by appending circle:: before its name :

sphere sph(1);
double s = sph.circle::surface();

Upvotes: 4

Related Questions