0

Is it legal to do so (this is just header files, and .cpp files contain the function definitions):

class Human
{
protected:
    std::string     m_name;
    int             m_age;

public:
    Human();
    void printName() const;
    void printAge() const;
};

And re-define the same void printName() const; (which is not virtual) in the derived class.

class Student : public Human
{
public:
    Student();
    void printName() const;
    void study() const;
};

What is this? This is not overriding. But it is not overloading too, right? As far as overloading should have different type or number of arguments (method is constant in both places). What have I done here?

Narek
  • 38,779
  • 79
  • 233
  • 389
  • 1
    This is known as 'Name hiding'. – ach Jun 07 '16 at 05:18
  • 1
    This is overloading; you can think of class methods as functions with first parameter of type `Myclass *` that automatically gets `this` sent to it when called. In your code each function has a different class for this parameter so it can overload. – M.M Jun 07 '16 at 05:28
  • @M.M exactly, this is the answer. – Narek Jun 07 '16 at 05:36
  • The linked Q (dupe) is about "different signature", while your Q is about "same signature". However the [answer](http://stackoverflow.com/a/411116/514235) for both the Qs is same as mentioned in other comments. The derived class methods simply hide the base class methods when they have same names. Other closely related Qs: [C++ inheritance with same function name](http://stackoverflow.com/q/13711790/514235), [When my base class and derived have the same function, does it HAVE to be virtual?](http://stackoverflow.com/q/19466662/514235). Hopefully these 3 posts are answering your Q. – iammilind Jun 07 '16 at 05:53

1 Answers1

0

Simple answer: yes.

More complex answer: yes, with a codicil:

Student s{};
s.printName();  // Will call Student::printName() const
Human &h = s;
h.printName();  // Will call Human::printName() const on same object

Since the methods aren't virtual, the compiler will call the method based on the type that the compiler sees at the point of the call.

The printName() method in Student is an override. But it is not a virtual override.

md5i
  • 3,018
  • 1
  • 18
  • 32