0

I tried running this code in the compiler and it gave an output of "circle":

#include <iostream>
using namespace std;

class figure{
    public:
    void print(){cout << "figure";};
};

class circle: public figure{
    public:
    void print(){cout << "circle";};
};

int main() {
    circle c;
    c.print();
}

I did not set the print function as a virtual yet it still had the same effect. Is there a reason for that?

AspiringMat
  • 2,161
  • 2
  • 21
  • 33
  • Call it with `((figure *)&c)->print();` and you will see the difference. – mch May 30 '17 at 12:48
  • You doing polymorphism wrong. Change `main` to `figure* foo = new circle; foo->print();` and see the difference. – NathanOliver May 30 '17 at 12:48
  • 2
    You used the function `Circle::print` and got the output of `Circle::print`. I see nothing wrong here. Did you mean to write `figure &f = c; f.print();`? – nwp May 30 '17 at 12:48
  • That's not overriding, that's *hiding*. The definition in `circle` *hides* the definition in `figure`. – Some programmer dude May 30 '17 at 12:48
  • @Someprogrammerdude So in other words, I can redefine functions inside the derived class without having them as virtual? – AspiringMat May 30 '17 at 12:50
  • @NathanOliver How is that any better? You introduced a dynamic memory allocation, pointer semantics and a memory leak when none of those were necessary. – nwp May 30 '17 at 12:50
  • This is totally NOT overriding. It's just name hiding. You have two functions that have the same name. Both are accessible. If you have an instance of circle, you can call figure::print() or circle::print() explicitly. – AlexG May 30 '17 at 12:51
  • Yes it's totally valid code. ***But*** it's not polymorphic. If you have a pointer or reference to the base class, and call the `print` function you will get the base class `print` function. – Some programmer dude May 30 '17 at 12:52
  • I see, thanks guys/gals. – AspiringMat May 30 '17 at 12:55

1 Answers1

0

As you did it, you only call the method print from the class circle. Try to do the following

int main() {
    figure* c = new circle();
    c->print();
    delete c;
}

and you will see figure, no more circle. As some people said, that's just name hidding. You define a new function in the class circle with the same name as the one in figure. Thus, when you call print on a circle object, you call its method.

Nevertheless, if print is a virtual method, you override the function. So, when you'll call print on a circle object, there will be only one function that can be called.

Abrikot
  • 965
  • 1
  • 9
  • 21