0

i mean, this code:

class A  
{ 
public:  
   void fun(); 
};
void A::fun() 
{ 
   cout << "fun() called"; 
} 

is basically doing the same job as this:

class A  
{ 
public:  
   void fun() 
{ 
   cout << "fun() called"; 
} 
}; 

right? are there any differences between these codes, any particular reason to choose the one over the other?

Mat
  • 202,337
  • 40
  • 393
  • 406
  • 1
    there is, the functions defined inside class are treated as inline functions, and functions defined outside class are treated as not inline, unless explicitly specified so. Also this feature has been provided so that we can separate the implementation part from the class declaration, like .hpp for class declaration, and .cpp for definition of functions. – Jugal Rawlani May 07 '20 at 15:55
  • 2
    Defining the function outside of the class lets you put the definition into a .cpp file. Not having it in the header improves build times, and means that you don't have to rebuild every file that includes the header if you modify the definition. – HolyBlackCat May 07 '20 at 15:55

1 Answers1

2

Imagine two classes:

class A {
public:
  A() { B b; }
};

class B {
public:
  B() { A a; }
};

That code as written cannot compile, because no matter how you order those classes, one of them refers to something not defined. You can't forward-declare one class either, because it gets instantiated.

This code, however, compiles:

class A {
public:
  A();
};

class B {
public:
  B();
};

A::A() { B b; }

B::B() { A a; }
Blindy
  • 65,249
  • 10
  • 91
  • 131