faressoft
faressoft

Reputation: 19651

Is it function overloading or overriding?

Is it function overloading or overriding or something else ? ( hello function )

class A {

public:
    void hello(int x) { cout << "A" << endl; }

};

class B : public A {

public:
    void hello() { cout << "B" << endl; }

};

void main() {

    B obj;
    obj.hello();

}

Upvotes: 1

Views: 1430

Answers (4)

MERLIN THOMAS
MERLIN THOMAS

Reputation: 837

It is not Overloaded Function because in Function Overloading either number of parameters or type of parameters should differ.For example :

void show(int a,int b);
void show(int a);
void show(char a,char b);

And neither it is Function Overriding because in Overridden function prototype must be same.For example : Base class and Derived class having function void show(); //function prototype must be same

Upvotes: 0

bames53
bames53

Reputation: 88185

Overriding:

struct Base {
    virtual void Foo() { std::cout << "Base\n"; };
};

struct Derived : Base {
    virtual void Foo() { std::cout << "Derived\n"; };
    // same name and signature as a virtual function in a base class,
    // therefore this overrides that function. 'virtual' is optional in
    // the derived class (but you should use it).
};

C++11 adds a way to ensure your function overrides:

struct Derived : Base {
    virtual void Foo() override { std::cout << "Derived\n"; };
};

Now if the method Foo is not overriding something then you will get an error.

struct Base {
   void Foo();
};

struct Derived : Base {
   virtual void Foo() override; // error, Derived::Foo is hiding Base::Foo, not overriding 
};

Upvotes: 2

Thirler
Thirler

Reputation: 20760

This is neither.

Overriding is a function with the same signature (same name, parameters and return value) in a subclass. Overloading is a function with the same name but different parameters.

Upvotes: 0

Luchian Grigore
Luchian Grigore

Reputation: 258618

It's neither, it's function hiding.

Declaring a non-virtual function with the same name (even if the signature is different) in a derived class hides the base class implementation completely.

To still have access to A::hello, you can do the following:

class B : public A {
public:
    using A::hello;
    void hello() { cout << "B" << endl; }
};

Overriding:

struct A
{
   virtual void foo() {}
};
struct B : public A
{
   /*virtual*/ void foo() {}
};

Overloading:

struct A
{
   void foo() {}
   void foo(int) {}
};

Upvotes: 9

Related Questions