The class method definition


The class method definition


Note :

Don't confuse with the methods and the functions.

These are the same thing the difference is that in Procedural oriented programming language
like 'C' these are 'functions'.

But when we use it in Classes that is object oriented programming these are called as methods.

So you should know about the functions, how they work, types and how de we declare them.
So if you dont know about these then first study about these in our C function tutorials :

Functions



The class method definition :

Member function in the class can be defined under the different access specifiers.

User can specify the code for the members in two different ways :

  • Inside the class definition
  • Outside the class definition

-Inside the class definition :

In this way the member function processes all the operations just as the simple function declaration.

Example :


#include <iostream.h>
#include <conio.h>

class Student
{
private:

int rollno;
float fee;

public:

void setRecord()
{
cout<<"Enter the rollno : ";
cin>>rollno;

cout<<"Enter the fee : ";
cin>>fee;

}

void display()
{
cout<<"\n\nRollno is : " << rollno;
cout<<"\nFee is : " << fee;

}

};

void main()
{
clrscr();

Student stud;

stud.setRecord();

stud.display();

getch();

}

Output :













Note :

The functions defined inside the class are inline functions. The functions defined in a class
specification are automatically inline.
Eg setRecord() and display() are the inline functions in the above code.

The advantage of inline function is that it saves the overheads of a function call i.e. time spent
in loading and unloading of the function call.

The concept for this is advantage is because the inline function tell the compiler to insert the
code for the body pof the function (method) at the place where it is called. Hence it saves the toverheads of the function call.

But inline function has its inherent drawbacks. We should define small functions inside the
class definition.
If the functions are large then we should call the functions outside the class definition.

- Outside the function call :

This is achieved by using the 'Scope Resolution Operator' . This is discussed in detail in
the next topic. So go to the next topic to study about it.




     Prev                                                   NEXT

0 comments:

Post a Comment