Differentiate between static and non-static members inside a class in C++?

When we have a method inside a class a class which does not use any data member of an instance and perform some operation with its own data is called as static method or class method.  Use static keyword to define the static methods.

Such method get called using class name along with special operator called as scope resolution operator (::)

The methods which take data from data members of an instance members are called as instance methods and alway require and instance to call them.

Example of Static method

Create a class Maths having a method factorial() which takes a number as argument and return factorial of that number.
Create an entry point and show the factorial of 7.

Solution

#include <iostream>
using namespace std;
class Maths
{
public:
static int factorial(int n)
{
if(n==0)
return 1;
else
return n*factorial(n-1);
}
};
main()
{
cout << Maths::factorial(7);
}

Output
5040

Example of instance method

Create a class Maths having a data member as num. Create a constructor to initalize data in num and a method factorial() which return factorial of  num.
Create an entry point and instance of Maths class then show the factorial of 7.

Solution

#include <iostream>
using namespace std;
class Maths
{
private:
int num;
public:
Maths(int num)
{
this->num=num;
}
int factorial()
{
int f=1,i;
for(i=1;i<=num;i++)
  f=f*i;
return f;
}
};
main()
{
Maths m(7);
cout << m.factorial();
}

Output
5040


Comments

Popular posts from this blog

What is template?

Can we access private members of an instance?

What are wrapper classes in Java?