How we can define and declare methods in C++?
Just like C language, we can declare and define methods of a class.
Here we declare the methods inside the class and define them outside the class.
It is sometimes required when we have many methods inside a class and they have long code. It is very difficult to identify the whole methods of a class.
Using scope resolution operator (::) to define a method outside the class.
Example
Create a class General having a data member as num. Declare a constructor inside the class and define it outside the class. Declare a method factorial() and define it outside the class.
Create an entry point to show factorial of 6.
Solution
#include <iostream>
using namespace std;
class General
{
private:
int num;
public:
General(int num);
int factorial();
};
General::General(int num)
{
this->num=num;
}
int General::factorial()
{
int f=1,i;
for(i=1;i<=num;i++)
f=f*i;
return f;
}
main()
{
General g(6);
cout << g.factorial();
}
Output
720
Here we declare the methods inside the class and define them outside the class.
It is sometimes required when we have many methods inside a class and they have long code. It is very difficult to identify the whole methods of a class.
Using scope resolution operator (::) to define a method outside the class.
Example
Create a class General having a data member as num. Declare a constructor inside the class and define it outside the class. Declare a method factorial() and define it outside the class.
Create an entry point to show factorial of 6.
Solution
#include <iostream>
using namespace std;
class General
{
private:
int num;
public:
General(int num);
int factorial();
};
General::General(int num)
{
this->num=num;
}
int General::factorial()
{
int f=1,i;
for(i=1;i<=num;i++)
f=f*i;
return f;
}
main()
{
General g(6);
cout << g.factorial();
}
Output
720
Comments
Post a Comment