Monday, April 27, 2015

Static Members inside a C++ Class , there is no static class in C++

We can define class members static using static keyword. When we declare a member of a class as static it means no matter how many objects of the class are created, there is only one copy of the static member.
A static member is shared by all objects of the class. All static data is initialized to zero when the first object is created, if no other initialization is present. We can't put it in the class definition but it can be initialized outside the class as done in the following example by redeclaring the static variable, using the scope resolution operator :: to identify which class it belongs to.

#include<iostream>
#include<conio.h>
#include<string>

using namespace std;

class TemperatureConverter
{
public :
static double CelsiusToFahrenheit(std::string temperatureCelsius)
{
// Convert argument to double for calculations. 
std::string::size_type sz; 
double celsius = std::stod(temperatureCelsius, &sz);

// Convert Celsius to Fahrenheit. 
double fahrenheit = (celsius * 9 / 5) + 32;

return fahrenheit;
}

static double FahrenheitToCelsius(std::string temperatureFahrenheit)
{
// Convert argument to double for calculations. 
std::string::size_type sz;
double fahrenheit = std::stod(temperatureFahrenheit, &sz);

// Convert Fahrenheit to Celsius. 
double celsius = (fahrenheit - 32) * 5 / 9;

return celsius;
}
};

void main()
{
cout<<"Please select the convertor direction\n";
cout << "1. From Celsius to Fahrenheit.\n";
cout << "2. From Fahrenheit to Celsius.\n";
cout << ":";

string selection;
int selectionType;
cin >> selection;
double F, C = 0;

if (selection.compare("1") == 0)
{
selectionType = 1;
}
else if (selection.compare("2") == 0)
{
selectionType = 2;
}
else
{
selectionType = 3;
}

std::string value;

switch (selectionType)
{
case 1:
cout<<"Please enter the Celsius temperature:";
cin >> value;
F = TemperatureConverter::CelsiusToFahrenheit(value);
printf("Temperature in Fahrenheit:%0.2f",F);
break;

case 2:
cout << "Please enter the Fahrenheit temperature:";
cin >> value;
C = TemperatureConverter::FahrenheitToCelsius(value);
printf("Temperature in Celsius:%0.2f", C);
break;

default:
cout << "Please select a convertor.";
break;
}

// Keep the console window open in debug mode.
cout <<"\nPress any key to exit.";
_getch();
}

No comments:

Post a Comment