Member Functions in Classes
There are 2 ways to define a member function:
- Inside class definition
- Outside class definition
To define a member function outside the class definition we have to use the scope resolution:: operator along with the class name and function name.
C++
// C++ program to demonstrate function // declaration outside class #include <bits/stdc++.h> using namespace std; class Geeks { public : string geekname; int id; // printname is not defined inside class definition void printname(); // printid is defined inside class definition void printid() { cout << "Geek id is: " <<id; } }; // Definition of printname using scope resolution operator :: void Geeks::printname() { cout << "Geekname is: " <<geekname; } int main() { Geeks obj1; obj1.geekname = "xyz" ; obj1.id=15; // call printname() obj1.printname(); cout << endl; // call printid() obj1.printid(); return 0; } |
Geekname is: xyz Geek id is: 15
Note that all the member functions defined inside the class definition are by default inline, but you can also make any non-class function inline by using the keyword inline with them. Inline functions are actual functions, which are copied everywhere during compilation, like pre-processor macro, so the overhead of function calls is reduced.
Note: Declaring a friend function is a way to give private access to a non-member function.
C++ Classes and Objects
Class in C++ is the building block that leads to Object-Oriented programming. It is a user-defined data type, which holds its own data members and member functions, which can be accessed and used by creating an instance of that class. A C++ class is like a blueprint for an object. For Example: Consider the Class of Cars. There may be many cars with different names and brands but all of them will share some common properties like all of them will have 4 wheels, Speed Limit, Mileage range, etc. So here, Car is the class, and wheels, speed limits, and mileage are their properties.
- A Class is a user-defined data type that has data members and member functions.
- Data members are the data variables and member functions are the functions used to manipulate these variables together, these data members and member functions define the properties and behavior of the objects in a Class.
- In the above example of class Car, the data member will be speed limit, mileage, etc, and member functions can be applying brakes, increasing speed, etc.
An Object is an instance of a Class. When a class is defined, no memory is allocated but when it is instantiated (i.e. an object is created) memory is allocated.