Jun 16, 2013 at 6:53pm UTC
Hi friends i m not sure whether i can define a member function inside a class or not in C++. Is the following code is legal?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
#include<iostream> using namespace std;
class adder
{
private :
int a;
int b;
int c;
int answer;
public :
void getNums()
{
cout<<"enter numbers:" <<endl;
cin>>a>>b>>c;
}
void showRes()
{
answer=a+b+c;
cout<<'' Sum of the numbers: '' <<answer<<endl;
}
};
Last edited on Jun 16, 2013 at 6:58pm UTC
Jun 16, 2013 at 6:57pm UTC
Does it compile?
The answer to the above question is the same as the answer to your question.
Jun 16, 2013 at 7:07pm UTC
There is no problem to define a member function within a class definition.
Jun 17, 2013 at 6:33am UTC
Script Coder wrote:Does it compile?
The answer to the above question is the same as the answer to your question.
While that is true in this case... I wouldn't pitch that as if it were a golden rule to go by.
A lot of non-standard code that
shouldn't work often compiles and does "work". Especially on older compilers.
So IMO we shouldn't discourage people from asking whether or not something is legal.
Last edited on Jun 17, 2013 at 6:33am UTC
Jun 17, 2013 at 5:52pm UTC
However a template member function may not be defined within a local class definition.:)
Jun 17, 2013 at 11:43pm UTC
u can define a member function inside a class.