Let’s assume we have a class ‘Arithmetic’ with two member functions Add() and Subtract(). Suppose Add() function is defined within class then how will the subtract() function be defined out of the class boundary. Explain it with the help of some suitable program.
Defining a function outside class
To define a function outside the class, it must be declared inside the class and then defined outside the class.
Syntax for function definition
return_type function_name(args);
Syntax for function definition
return_type class_name :: function_name (args)
{
// function definitions
}
Example
#include <iostream>
using namespace std;
class Arithmetic { // The class
public: // Access specifier
int x=10;
int y=6;
//define the function add inside the class
void Add(){
cout<<x+y<<endl;
}
void Subtract(); //function declaration
};
// function definition outside the class
void Arithmetic::Subtract() {
cout<<x-y;
}
int main() {
Arithmetic a; // Create an object of Arithmetic
a.Subtract(); // Call the method Subtract
a.Add(); //call the method Add
return 0;
}
Comments
Leave a comment