• 0

C++ A meaning of static


Question

I was reading the Head First Design Patterns Silver C++ translation and came across this:

#ifndef	_HFDP_CPP_VISITOR_INGREDIENT_HPP_
#define _HFDP_CPP_VISITOR_INGREDIENT_HPP_

namespace HeadFirstDesignPatterns {
namespace Visitor {
namespace Menus {

// recommended daily values
static const float dailyCalories = 2000.0f;
static const float dailyCarbs = 300.f;
static const float dailyCholesterol = 0.300f;
static const float dailyFat = 65.0f;
static const float dailyProtien = 50.0f;
static const float dailySodium = 2.400f;

class Visitor;

class Ingredient : MenuComponent {

	protected: float _amount;

	protected: Ingredient( float amount = 1.0f ) :
		_amount( amount ) { assert( amount > 0.0f );
	}
	public: virtual ~Ingredient() = 0 {
	}
	public: virtual void add( MenuComponent* menuComponent ) {
	}
	public: virtual void accept( Visitor* visitor ) = 0;
	public: virtual bool isVegetarian() const = 0;
	public: virtual float getCalories() const = 0;
	public: virtual float getCarbs() const = 0;
	public: virtual float getCholesterol() const = 0;
	public: virtual float getFat() const = 0;
	public: virtual float getProtien() const = 0;
	public: virtual float getSodium() const = 0;
	public: virtual float getHealthRating() const {
		float result = 0.0f;

		result += getCalories() / dailyCalories;
		result += getCarbs() / dailyCarbs;
		result += getCholesterol() / dailyCholesterol;
		result += getProtien() / dailyProtien;
		result += getSodium() / dailySodium;

		return _amount * ( result * 100.0f );
	}
	public: virtual std::string toString() const = 0;
};

} // namespace Menus
} // namespace Vistor
} // namespace HeadFirstDesignPatterns

#endif

What bugs me are the static const float declarations. First, even though they are in the class header file, they are not part of the class declaration. My first serious introduction to programming was VB.NET and C# and I am still confused with things being declared outside of classes. How is their scope defined? And what does the keyword static mean in this place?

Thanks.

Link to comment
https://www.neowin.net/forum/topic/651152-c-a-meaning-of-static/
Share on other sites

10 answers to this question

Recommended Posts

  • 0

A static variable is a variable that holds its value until the end of execution. For example, if you have a static variable inside a function, even when the function ends, that variable will still hold its value.

A static property is a property that is shared among all objects. I will give you an example to clarify the image.

Lets say that you have a class called MyClass and you want to count how many objects have been inistantiated. If you had a property that is not declared as static, on each object creation that property will lose its data and it will be 1 among all objects. However, if it was static, it would increase on each object creation (Given that you're increazing the property in the constructor).

Hopefully I was able to help you out. I don't remember C++ syntax (long, long time since I coded with C++).

EDIT: I forgot to mention that you refer to the static property by Class name, and not by the object itself, remember, it's shared among all objects.

  • 0
Thanks, I get what static means inside classes. What I have difficulty understanding is what it does outside of classes like in this case. And also how the scope of variables or functions declared outside of classes is determined.

It's essentially a global, but it is differentiated by the namespace so you could have 2 or more dailyCalories defined within the project and the names won't collide.

#include "Ingredient.h"
#include <iostream>

using namespace std;

static const float dailyCalories = 1800.0f;
int main(void){
	cout << HeadFirstDesignPatterns::Visitor::Menus::dailyCalories << '\n'; // outputs 2000
	cout << "Global ::" << ::dailyCalories << endl; // outputs 1800
}

  • 0
If it's global that means everyone has read/write access to it, as long as the file in which is declared is #included? Also, what difference does it make that this global is declared static?

1. Yes if it isn't declared const.

2. It's only allocated once when the file is loaded and deallocated when the file is unloaded

  • 0
2. It's only allocated once when the file is loaded and deallocated when the file is unloaded
This is what I don't get: if a variable is global, then how can it ever be allocated more than once? If by being global it can only be allocated once, what is the purpose of writing static? Also, what do you mean that "the file is unloaded"?
  • 0
Objects do not have static data, since static data is class level.

that is why you cannot do the following

public static int x;

object.x

You call static data by the class

Thats what he means when its allocated once, since objects cannot hold that data.

Sorry but we were talking about global variables, look at the static variables in the example, they are declared outside of a class. What does static mean in this case?
  • 0
This is what I don't get: if a variable is global, then how can it ever be allocated more than once? If by being global it can only be allocated once, what is the purpose of writing static? Also, what do you mean that "the file is unloaded"?

There is more than one concept happening here; scope and linkage, which is the source of much confusion for not only you. :)

This may help:

http://publib.boulder.ibm.com/infocenter/c...ref/cplr020.htm

  • 0
There is more than one concept happening here; scope and linkage, which is the source of much confusion for not only you. :)

This may help:

http://publib.boulder.ibm.com/infocenter/c...ref/cplr020.htm

Not another set of obscure complex C++ rules!!! When is this going to end!!! Arrrrghlg.. *boom

On a more grateful note, thanks, this goes on my to-read list. :laugh:

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Posts

    • Samsung messages is still alive and well. They reversed that and decided to our more effort into it.
    • I think every American should have a course in a 'dry sense of humour' at school; and perhaps 'using sarcasm in jest' oh, and also 'the use or irony in humour'.
    • What they really need to do is automatically spell "loses" and "lose" correctly since nobody seems to know how to anymore. Then they blame spellcheck/autocomplete and don't realize autocomplete is just filling in the word for them automatically so it was misspelled in the first place.
    • If someone chooses to continue using SB and therefore goes through the manual intervention in the thread, afterwards the BSOD problem is gone. Whether they then re-enable the task doesn't matter, they're done, though on such machines it might pay to keep it disabled in case the next update (if there is a next) causes the same problem. OTOH, if someone disables SB in the BIOS, the problem is also gone. Incidentally, I noticed that this task exists even on machines that don't support SB. It's just installed across the board...and runs. Doing what on such machines is a little hazy.
    • qBittorrent 5.2.2 by Razvan Serea The qBittorrent project aims to provide a Free Software alternative to µtorrent. qBittorrent is an advanced and multi-platform BitTorrent client with a nice user interface as well as a Web UI for remote control and an integrated search engine. qBittorrent aims to meet the needs of most users while using as little CPU and memory as possible. qBittorrent is a truly Open Source project, and as such, anyone can and should contribute to it. qBittorrent features: Polished µTorrent-like User Interface Well-integrated and extensible Search Engine Simultaneous search in most famous BitTorrent search sites Per-category-specific search requests (e.g. Books, Music, Movies) All Bittorrent extensions DHT, Peer Exchange, Full encryption, Magnet/BitComet URIs, ... Remote control through a Web user interface Nearly identical to the regular UI, all in Ajax Advanced control over trackers, peers and torrents Torrents queueing and prioritizing Torrent content selection and prioritizing UPnP / NAT-PMP port forwarding support Available in ~25 languages (Unicode support) Torrent creation tool Advanced RSS support with download filters (inc. regex) Bandwidth scheduler IP Filtering (eMule and PeerGuardian compatible) IPv6 compliant Available on most platforms: Linux, Mac OS X, Windows, OS/2, FreeBSD qBittorrent 5.2.2 changelog: FEATURE: Use D-Bus to show file in file managers (Chocobo1) #24340 BUGFIX: Fix friendlyUnitCompact precision calculation (vafada) #24323 BUGFIX: Remove all top-level folders (glassez) #24333 BUGFIX: Use proper API for checking exit status (Chocobo1) #24349 BUGFIX: Delete stale lockfile when hostname mismatch (TurboTheTurtle, glassez) #24363 BUGFIX: Fix wrong removal procedure of watched folder paths (Chocobo1) #24413 BUGFIX: Don't reannounce before interface changes are applied (glassez) #24447 BUGFIX: Use Latin script for Bosnian locale name (Andy Ye) #24342 WEBUI: Fix performance of global checkbox toggling (tehcneko) #24316 WEBUI: Fix Safari transfer list header misalignment (Piccirello) #24377 WEBUI: Fix error when submitting magnet before metadata loads (Piccirello) #24378 WEBUI: Use correct row id when updating Rss Downloader feed selection (Chocobo1) #24402 WEBUI: Use SameSite=Lax for session cookie to fix cross-site login (Piccirello) #24422 WEBUI: Bring back properties panel expand/collapse button (vafada) #24430 WEBAPI: Only use X-Forwarded-Host header when reverse proxy support is enabled (Chocobo1) #24457 RSSS: Fix "RSS Smart Episode Filter" RegEx (nathanon-akk, glassez) #24398 RSS: Fix previously matched episode format (glassez) #24452 WINDOWS: Fix Python fallback search path (TurboTheTurtle) #24325 WINDOWS: NSIS: Allow to install x64 binary on ARM64 (Chocobo1) #24358 Download: qBittorrent 5.2.2 | 41.1 MB (Open Source) Download: qBittorrent 64-bit installer (qt6) | 43.6 MB Links: qBittorrent Home page | Screenshot Get alerted to all of our Software updates on Twitter at @NeowinSoftware
  • Recent Achievements

    • Veteran
      branfont went up a rank
      Veteran
    • Reacting Well
      Almohandis earned a badge
      Reacting Well
    • First Post
      Cosminus earned a badge
      First Post
    • One Year In
      ThatGuyOnline earned a badge
      One Year In
    • Week One Done
      Jeroen Wilms earned a badge
      Week One Done
  • Popular Contributors

    1. 1
      +primortal
      498
    2. 2
      +Edouard
      185
    3. 3
      PsYcHoKiLLa
      126
    4. 4
      Steven P.
      87
    5. 5
      neufuse
      72
  • Tell a friend

    Love Neowin? Tell a friend!