Codes Academy

MEMBER FUNCTIONS IN CLASSES

MEMBER FUNCTIONS IN CLASSES

C++
Member functions are the functions, which have their declaration inside the class definition and works on the data members of the class. The definition of member functions can be inside or outside the definition of class.
Member functions are the functions, which have their declaration inside the class definition and works on the data members of the class. The definition of member functions can be inside or outside the definition of class.
If the member function is defined inside the class definition it can be defined directly, but if its defined outside the class, then we have to use the scope resolution :: operator along with class name alng with function name.
Example :
class Cube
{ public:
int side;
 int getVolume();     // Declaring function getVolume with no argument and return type int.
};
If we define the function inside class then we don't not need to declare it first, we can directly define the function.
class  Cube{
public:
 int side;
 int getVolume()
 {  return side*side*side;       //returns volume of cube
 }
};
But if we plan to define the member function outside the class definition then we must declare the function inside class definition and then define it outside.
class Cube
{ public:
 int side;
 int getVolume();
}
int Cube :: getVolume()     // defined outside class definition
{
 return side*side*side;
}
The maine function for both the function definition will be same. Inside main() we will create object of class, and will call the member function using dot (.) operator.
int main()
{
 Cube C1;
 C1.side=4;   // setting side value
 cout<< "Volume of cube C1 ="<< C1.getVolume();
}
Similarly we can define the getter and setter functions to access private data members, inside or outside the class definition.
Thank  you guys for reading my blogs .
Thank you


Follow me on social  sites :
Ø      Follow me on google  plus.

0 comments:

Post a Comment