Topic1: Passing and Returning Objects in C++
In C++ we can pass class’s objects as arguments and also return them from a
function the same way we pass and return other variables. No special keyword or
header file is required to do so.
Passing an Object as argument
To pass an object as an argument we write the object name as the argument while
calling the function the same way we do it for other variables.
Syntax:
function_name(object_name);
class Example {
public:
int a;
// This function will take
// an object as an argument
void add(Example E)
{
a = a + E.a;
}
};
int main()
{
// Create objects
Example E1, E2;
// Values are initialized for both objects
E1.a = 50;
E2.a = 100;
cout << "Initial Values \n";
cout << "Value of object 1: " << E1.a
<< "\n& object 2: " << E2.a
<< "\n\n";
// Passing object as an argument
// to function add()
E2.add(E1);
cout << "New values \n";
cout << "Value of object 1: " << E1.a
<< "\n& object 2: " << E2.a
<< "\n\n";
return 0;
}
Topic 2: Returning Object as argument
Syntax:
object = return object_name;
function returns an object of type class
#include <bits/stdc++.h>
using namespace std;
class Example {
public:
int a;
// This function will take
// object as arguments and
// return object
Example add(Example Ea, Example Eb)
{
Example Ec;
Ec.a = Ec.a + Ea.a + Eb.a;
// returning the object
return Ec;
}
};
int main()
{
Example E1, E2, E3;
// Values are initialized
// for both objects
E1.a = 50;
E2.a = 100;
E3.a = 0;
cout << "Initial Values \n";
cout << "Value of object 1: " << E1.a
<< ", \nobject 2: " << E2.a
<< ", \nobject 3: " << E3.a
<< "\n";
// Passing object as an argument
// to function add()
E3 = E3.add(E1, E2);
// Changed values after
// passing object as an argument
cout << "New values \n";
cout << "Value of object 1: " << E1.a
<< ", \nobject 2: " << E2.a
<< ", \nobject 3: " << E3.a
<< "\n";
return 0;
}
Topic 3: Inline Function
C++ inline function is powerful concept that is commonly used with
classes. If a function is inline, the compiler places a copy of the code of
that function at each point where the function is called at compile time.
Any change to an inline function could require all clients of the function to
be recompiled because compiler would need to replace all the code once
again otherwise it will continue with old functionality.
To inline a function, place the keyword inline before the function name
and define the function before any calls are made to the function. The
compiler can ignore the inline qualifier in case defined function is more
than a line.
A function definition in a class definition is an inline function definition,
even without the use of the inline specifier.
#include <iostream>
using namespace std;
inline int Max(int x, int y) {
return (x > y)? x : y;
}
// Main function for the program
int main() {
cout << "Max (20,10): " << Max(20,10) << endl;
cout << "Max (0,200): " << Max(0,200) << endl;
cout << "Max (100,1010): " << Max(100,1010) << endl;
return 0;
}