J's Study log

[C++] Function Overloading & Overriding 본문

Computer Language/C++

[C++] Function Overloading & Overriding

정우섭 2020. 3. 22. 23:39

Overloading

  • Name of the method must be same
  • Return type can be same or not
  • Number of the parameter should be different
  • If the number of the parameter is same, the type of the parameter must be different

 

#include <iostream>
using namespace std;

void func(int i)
{
	cout << "func(int) is called." << endl ;
}

void func(char c)
{
	cout << "func(char) is called." << endl;
}

void func(int i, int j)
{
	cout << "func(int, int) is called." << endl;
}

/*
int func(int i)
{
	cout << "int func(int) is called." << endl;
}
*/

int main()
{
	func(1);
	func('a');
	func(2, 3);
}

 

 

You can declare overloading functions like this code.

 

But if you unlock the annotation there will be errors after.

 

Because 'Just a different return type is not allowed to overload a function'.

 

void func(int a) and int func(int a) is not overloaded fuctions.

 

 

 

 

 

 

Overriding

  • Method that you override must be already declared in the base class
  • Name of the method must be same
  • The parameter of method must be same. (type and number of the parameter)
  • Return type must be same
  • Overrided method need to have something more or at least same with the base.

 

#include <iostream>
using namespace std;

class Base
{
public:
	void func()
	{
		cout << "B::func() is called" << endl;
	}
};

class Derived : public Base
{
public:
	void func()
	{
		cout << "D::func() is called" << endl;
		//Base::func();
	}
};

int main()
{
	Base b;
	Derived d;

	b.func();//result, B::func() is called
	d.func();//result, D::func() is called
}

 

Redefinition of a function to add what it needs and make something different from the based one.

 

(And of course you can call the base class's function like line19)

 

 

 

 

 

 

 

 

[참고자료]

- 윤성우의 열혈 C++ 프로그래밍

'Computer Language > C++' 카테고리의 다른 글

[C++] Virtual Function  (0) 2020.04.01
[C++] Reference Relation of Object Pointer  (0) 2020.03.27
[C++] call by value & call by reference  (0) 2020.03.21
Effective C++  (0) 2020.03.10
[C++] Inheritance  (0) 2020.03.10
Comments