Answer to Question #185800 in C++ for bilal

Question #185800

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. 


1
Expert's answer
2021-04-26T14:00:26-0400

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;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS