Members of Class in C++

Types of members inside a class

 

  • The class can have two kind of members
    • Static or Class Members
    • Non-Static or instance member

 

Class members are shared members that anybody can access using the class name and do not require an object. Use static keyword to declare such members. Use scope resolution operator  (::) to access such members. 

Non-static or instance members always need an object to call them using dot operator (.)

All class or static members are stored in heap memory. Note that all objects are also stored in heap memory. On the other hand all the non-static or instance members and functions are stored in stack memory

 

We will understand this by an example. Let’s create a class num2 having two fields a and b, also a constructor to initialize these fields and  a method as product() which returns product of a and b. Let’s also create another method as factorial() which takes a number as argument and returns the factorial of that number.

 

 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
31
32
#include<iostream.h> // For input/output operations
#include<conio.h> // For clrscr() function
class num2 // We declare a class with name “num2”
{
    int a,b;
    public: // Access Modifier
        num2(int a, int b) // Now there are two variables with name a & b
        {
            this->a=a; // Note the usage of this right hand ‘a’ is member of method
            this->b=b; // this keyword ensures b is topmost class scope member
        }
        int product()
        {
            return a*b; // this is not needed as ‘a’ and ‘b’ are only one member
        }
        static  long factorial(int n)
        {
               if(n==1)
                return 1;
               else
                return n*factorial(n-1); // Remember recursion famous example ? 
        }
};
void main()
{
    num2 p(4,5),q(5,7);
    clrscr();
    cout << p.product() << endl;
    cout << q.product() << endl;

    cout << num2::factorial(6); // :: is scope resolution operator
}

 

Using this pointer

  • this pointer refers the current object of a class
  • It is mainly used when parameter name and field names are same