C++ 26: Defining member function outside the class

 Defining member Functions outside the class

1.To increase the readability pf the program we can define the member fuctions,
  constructors, etc. of a class out side the class.
2.If we want to define member function outside the cass then we must define 
  the prototype of member function inside the class
3. The member function can be define outside the class as following

Syntax:
return_type class_name ::function_name(data_type arg1, data_type arg2, ...)
{
                ........
                ........
}


Example:
Design a Class Rectangle with data members L & B. Define member function area(),perimeter();
The objects of class must be created  by passing data. Define all the constructors and 
member functions outside the Class.

#include <iostream>
using namespace std;
class Rectangle
{
private:
    int LB;

public:
    Rectangle(intint);
    void area();
    void perimeter();
};

Rectangle::Rectangle(int l, int b)
{
    L = l;
    B = b;
}

void Rectangle::area()
{
    int area = L * B;
    cout << "Area of Rectangle is: " << area << endl;
}
void Rectangle::perimeter()
{
    int perimeter = 2 * (L + B);
    cout << "Area of Rectangle is: " << perimeter << endl;
}
int main()
{
    Rectangle a(1020);
    a.area();
    a.perimeter();

    return 0;
}

Output:

Area of Rectangle is: 200
Area of Rectangle is: 60


Example 2:
Design a class Distance with data members Feet and and Inches. Define a 
member functions convert(),showdata().
The convert() will convert Distance object into inches(1 Feet = 12 Inches) 
The objects of the class must be created by passing 2,1,0 argruments.Define
 all member functions and constructions outside the class

























#include <iostream>
using namespace std;
class Distance
{
private:
    int FI;

public:
    Distance(intint);
    void showdata();
    int convert();
};

Distance::Distance(int f = 0int i = 0)
{
    F = f;
    I = i;
}

void Distance::showdata()
{
    cout << "Distance is Feet : " << F << " and Inches: " << I << endl;
}

int Distance::convert()
{
    int inches;
    inches = I + (F * 12);
    return inches;
}
int main()
{
    int totalinches;
    Distance a(424);
    a.showdata();
    totalinches = a.convert();
    cout << "Total distance in Inches is : " << totalinches << endl;

    return 0;
}

Output:

Distance is Feet : 4 and Inches: 24
Total distance in Inches is : 72


Comments

Popular posts from this blog

C++ 38: Visibility Modes Public, Private and Protected