This C++ program demonstrates the use of static members in a class. A static data member is shared by all objects of a class. We can put a static data member inside a class but we would have to initialize it outside the class using scope resolution operator (::).
Here is the source code of the C++ program demonstrates the use of static members in a class. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.
/*
* C++ Program to Demonstrate a Class with Static Members
*/
#include <iostream>
class Car {
private:
static std::string colour;
std::string brand;
std::string state;
int model;
public:
Car(int model, std::string brand, std::string state = "off")
{
this->model = model;
this->brand = brand;
this->state = state;
}
void engineOn()
{
state = "on";
}
void knowState()
{
std::cout << "Is " << brand << " ready?" << std::endl;
}
void isReady()
{
if(state == "on")
std::cout << colour << " " << brand
<< " is ready to go!" << std::endl;
else
std::cout << colour << " " << brand
<< " is not ready!" << std::endl;
}
};
// Definition of a protected static member
// Legal expression
std::string Car::colour = "Red";
int main()
{
Car chevy(1965, "Chevy Mint", "on");
chevy.knowState();
chevy.isReady();
Car ferrari(1965, "Ferrari" );
ferrari.knowState();
ferrari.isReady();
}
$ a.out Is Chevy Mint ready? Red Chevy Mint is ready to go! Is Ferrari ready? Red Ferrari is not ready!
Sanfoundry Global Education & Learning Series – 1000 C++ Programs.
advertisement
If you wish to look at all C++ Programming examples, go to C++ Programs.
Related Posts:
- Apply for Computer Science Internship
- Check Programming Books
- Check Computer Science Books
- Practice Programming MCQs
- Apply for C++ Internship