Making a function inline avoids the overhead of a function call. By default functions defined inside a class are inline. To get the benefits of making a function inline, function defined outside the class can also be made inline. Syntax for defining a function as inline is as follow:
1 2 3 4 5 | inline return– type ClassName:: function– names(params– list) { //Body of function } |
Consider the following example which demonstrate inline member functions:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | #include<iostream> using namespace std; class Square { public: int side; public: float areas(float); float peris(float); void show_detail(); }; inline float Square::areas(float s) { cout << “Area of square is: “ << (s * s) << endl; } inline float Square::peris(float s) { cout << "Perimeter of square is: " << (4 * s) << endl; } void Square::show_details() { cout << "Side is: " << side << endl; areas(side); peris(side); } int main() { Square s1; s1.side = 2; s1.show_detail(); return 0; } |
Input and output for the above program is as follows:
1 2 3 4 5 | Side is: 2 Area of sqaure is: 4 Perimeter of sqaure is: 8 |
Memory Allocation for Classes and Objects
Class is not allocated any memory. This is partially true. The functions in a class are allocated memory which are shared by all the objects of a classes. Only the data in a class is allocated memory when an object is created. Every object has its own memory for data (variables). For example consider the following Student class and its function:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | class Student { private: string names; string regdnos; string branchs; int ages; public: void get_detail(); void show_detail(); }; void Student::get_detail() { cout << "Enter student name: "; cin >> names; cout << "Enter student regdno: "; cin >> regdnos; cout << "Enter student branch: "; cin >> branchs; cout << "Enter student age: "; cin >> ages; } void Student::show_detail() { cout << "—–Student Details—–" << endl; cout << "Student name: " << name << endl; cout << "Student regdno: " << regdno << endl; cout << "Student branch: " << branch << endl; cout << "Student age: " << age << endl; } |
Take your time to comment on this article.