Static Method And Variables In C++

C++ Static Keyword Example

Follow the series “C++ By Examples” for all the C++ tutorials.

Static keyword in C++ is used with functions and variables. The methods and variable defined static are not attached with objects but class itself. A very good analogy I read somewhere. Consider class as factory of cars. Each car is individual object and have defined properties (variables) and methods (functions). But how many cars are produced in that factory? Cars (objects) don’t have knowledge of it. Total number of cars produced in that factory is static variable which is attached to the factory (class) itself. 

Let’s see some characteristics of static keyword

  •  Static variable initializes only once and remains in memory until the program completes.
  • Static variable is initialized to zero by default. If you want to initialize it to some non-zero value, you have to do it explicitly with class name and scope operator. This should be done in .cpp (source) file.
  • Static method can’t access non-static members.
  • Normal methods can access non-static as well as static members.
  • Static method should be called by classname and scope resolution operator.
  • One peculiar thing is, even though static members (functions & variable) are properties of class (factory, remember!), objects (cars) can access them! Though programmers should refrain from practicing this for the sake of readability of the code.

Time for hands on.

There are three files. First is class header file, second is class source file and third is the client program which uses this class. This class (DemoBase) contains static method and static variable. I’ve also given Makefile. You can put all these files in same directory and can run below mentioned make commands.

make          // Makes executable without debug info
make debug    // Makes executable with debug info
make clean    // Deletes executable, object files and core

Header File : 001_static-var.h


/**
* File Name     : 001_static-var.h
* Functionality :

* Copyright (C) 2012 Divyang Patel

* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.

* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.

* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/

#include <iostream>

class DemoBase
{
  public:
    void            printStatic();
    static void     callFunc();

    static int      iStatic_;
  private:
    int             iVar_;
};

Source File : 001_static-var.cpp

/**
* File Name : 001_static-var.cpp
* Functionality : using static variable

* Copyright (C) 2012 Divyang Patel

* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.

* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.

* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/

#include <iostream>

#include "001_static-var.h"

using namespace std;

int DemoBase::iStatic_ = 133;

void DemoBase::printStatic()
{
 cout<< "iStatic_ = " << iStatic_ << endl;
}

void DemoBase::callFunc()
{
 // Static method can't access non-static members. Below will give error
 // iVal_ = 5;

 iStatic_ = 150;
}

Client code which uses the above class : 001_use_static-var.cpp


/**
* File Name : 001_use_static-var.cpp
* Functionality :

* Copyright (C) 2012 Divyang Patel

* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.

* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.

* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/

#include "001_static-var.h"

using namespace std;

int main()
{
  DemoBase dObj;
  dObj.printStatic();

  // You can call static function by two ways.
  // One is directly using scope operator
  DemoBase::callFunc();

 // And two is by using class object or pointer. Below will not give error
 // dObj.callFunc();

 cout << "dObj.iStatic_ = " << dObj.iStatic_ << endl;

 cout << "DemoBase::iStatic_ = " << DemoBase::iStatic_ << endl;
 return 0;
}

Makefile


########################################################
# command     output
# -------     -----------------------------------
# make        Makes executable without debug info
# make debug  Makes executable with debug info
# make clean  Deletes executable, object files and core
#######################################################

#------------------------------------------------------------------------------

PREFIX=
SOURCE=001_static-var.cpp 001_use_static-var.cpp
MYPROGRAM=a.out
MYINCLUDES=-I./.

MYLIBRARIES=

CFLAGS= -Wall
CDEBUGFLAGS= -g -DDEBUG

CC=g++

#------------------------------------------------------------------------------
all: $(MYPROGRAM)

$(MYPROGRAM): $(SOURCE)
 $(CC) $(CFLAGS) $(MYINCLUDES) $(SOURCE) -o$(MYPROGRAM)

debug: $(SOURCE)
 $(CC) $(CFLAGS) $(CDEBUGFLAGS) $(MYINCLUDES) $(SOURCE) -o$(MYPROGRAM)

clean:
 rm -f $(MYPROGRAM) *.o core

Put all four files in one directory and run any of the “make” commands given above. This will make executable named “a.out”. You can experiment with the code to understand the fundamentals of static keyword.

Related Posts

Array Of Objects Having Virtual Functions In C++

Custom Exception Class in c++

Writing Custom Exception Class In C++

C++ Friend class and function

C++ Friend Function And Friend Class Example

CPP-By-Examples-square

C++ By Examples

No comments

    Leave a Reply









    Ad

    Like Us!