C++ static const integral variable usage via pointer/reference? - c++

When declaring and using static const integrals, I find it convenient and natural to use the object reference I'm working with to access the variable, rather than fully-qualifying it with the class name. I'm wondering if there is a downside to this? Take for example:
class MyLongClassNameIdRatherNotHaveEverywhere {
public:
static const int Len = 6;
//...
void otherInterestingThings();
void someWorkToDo();
};
int main() {
MyLongClassNameIdRatherNotHaveEverywhere *lcn = new MyLongClassNameIdRatherNotHaveEverywhere;
lcn->someWorkToDo();
cout << "the length is: " << lcn->Len << endl;
delete lcn;
return 0;
}
Notice the lcn->Len... it's really a constant, and in fact if lcn were null, lcn->Len would still compile and run just fine. I could have written MyLongClassNameIdRatherNotHaveEverywhere::Len there instead, which certainly makes it more obvious (to me at least) that this is a constant. Are there other drawbacks?

Apart from weirdness, I can see a drawback in case operator -> is overloaded...
Scope resolution operator :: btw, cannot be overloaded.

Related

Overhead of returning reference to member variable data

I am new to C++ and get confused about what goes on under the hood when a class method returns a reference to a member variable that is raw data (rather than a pointer or a reference). Here's an example:
#include <iostream>
using namespace std;
struct Dog {
int age;
};
class Wrapper {
public:
Dog myDog;
Dog& operator*() { return myDog; }
Dog* operator->() { return &myDog; }
};
int main() {
auto w = Wrapper();
// Method 1
w.myDog.age = 1;
cout << w.myDog.age << "\n";
// Method 2
(*w).age = 2;
cout << w.myDog.age << "\n";
// Method 3
w->age = 3;
cout << w.myDog.age << "\n";
}
My question is: what happens at runtime when the code reads (*w) or w-> (as in the main function)? Does it compute the address of the myDog field every time it sees (*it) or it->? Is there overhead to either of these two access methods compared to accessing myDog_ directly?
Thanks!
Technically, what you are asking is entirely system/compiler-specific. As a practicable matter, a pointer and a reference are identical in implementation.
No rational compiler is going to treat
(*x).y
and
x->y
differently. Under the covers both usually appears in assembly language as something like
y(Rn)
Where Rn is a register holding the address of x and y is the offset of y into the structure.
The problem is that C++ is built upon C which in turn is the most f*&*) *p programming language ever devised. The reference construct is a work around to C's inept method of passing parameters.

How to declare constant parameters in separate class or header file in C++?

My IDE is Microsoft Visual Studio 2017.
This is primitive example code:
main.cpp
#include <iostream>
#include "Klasa_00.h"
using namespace std;
int main() {
int const Number_0 = 234;
float const Number_1 = 34.76;
double const Number_2 = 98.78;
cout << "Number_0 is:" << Number_0 << endl;
cout << "Number_1 is:" << Number_0 << endl;
cout << "Number_2 is:" << Number_0 << endl;
system("Pause");
return 0;
}
Klasa_0.cpp
#include "Klasa_00.h"
Klasa_00::Klasa_00()
{
}
Klasa_00::~Klasa_00()
{
}
Klasa_0.h file
#pragma once
class Klasa_00
{
public:
Klasa_00();
~Klasa_00();
};
I am new in C++ programing so I need a help about making code. For example, in Fortran programing language all variables with parameter attribute can be declared in separate module which can be easily used in main program.
What I want to learn here is possibility of using that principle of coding in C++ or something similar.
So, in my case a have a three variables which i want to move into class Klasa_00.
Is there way or ways for doing that?
As others have said, you might want to avoid using classes to store your constants in other files, and you might simply wish to store them in a header (possibly with a namespace, more on that later). Having said that, I do understand that you might want a constant that belongs to a class, so I'll cover that case as well later in the answer.
The simplest way is to declare and define the constant in a header on its own as such:
// YourHeader.h
#ifndef YOUR_HEADER_H
#define YOUR_HEADER_H
[...]
const int aConstNumber = 1;
static const int anotherConstNumber = 2;
constexpr int aConstExprNumber = 3;
static constexpr int anotherConstExprNumber = 4;
[...]
#endif
// main.cpp
#include <iostream>
#include "YourHeader.h"
int main()
{
// You can simply access the variables by name as so:
std::cout << aConstNumber << "\n"; // 1
std::cout << anotherConstNumber << "\n"; // 2
std::cout << aConstExprNumber << "\n"; // 3
std::cout << anotherConstExprNumber << std::endl; // 4
}
These variables all behave the same logically, but they work in different ways. A variable declared with the const keyword is defined at runtime, and guaranties it won't change. A variable declared with the constexpr keyword, however, is defined at compile time.
So, while this means that if you had multiple classes with something like an ID (which shouldn't change, but should be unique), you'd prefer const over constexpr (since the latter wouldn't work in that context).
Let's talk about static as well. static means that there is a single shared instance of that variable across your classes. So if the Bar class has a static int ID value, all instances of Bar share the same ID value. Changing it once changes it for all instances. Though if it's a constant, you won't be able to change it.
In your case, if it's to define constants that are pre-defined and won't change, I'd strongly recommend using constexpr, since you can use those variables to do things you couldn't use a const variable for (like defining the size of an array).
Before you go ahead and do that, however, consider the following class.
class Foo
{
public:
const int a = 5; // Valid use of const.
constexpr int b = 7; // Invalid use of constexpr, won't even compile!
static constexpr int c = 10; // Valid use of constexpr.
int arrA[a]; // ERROR: 'a' is defined at runtime, so you can't use it to define a size.
int arrB[b]; // ERROR: You couldn't even define 'b', so this is not going to work...
int arrC[c]; // VALID: 'c' is known by the compiler, and is guaranteed to only ever be 10!
}
It is worth noting that if you wanted to access a or c (the only two valid variables declared and defined in your class), you'd have to use the following syntax, rather than just their names:
// "Foo" is their class' name, and represents their parent namespace.
std::cout << Foo::a << "\n"; // 5
std::cout << Foo::c << std::endl; // 10
As you can see, constexpr int b = 7; is invalid. Why though? Shouldn't it be seen by the compiler and work just fine? Well, no. You see, the issue is that maybe you'll never instantiate that class, right? const variables are fine, because they're defined at runtime, this means they don't have to exist, they just can't change once you've given them a value. constexpr on the other hand needs to be sure it'll exist, because it has to exist and be valid at compile time!
While declaring a constexpr variable is perfectly fine in a header file, it doesn't work unless you use the static keyword with it if you want to declare one in a class! Because the static keyword will let the compiler know that, regardless of how you instantiate this class, the variable's value will never change and it will be known at compile time thanks to constexpr!
I strongly recommend you read this post to understand just what static and constexpr do when combined.
If you have "constants" that are only constant once instantiated, go with const.
If you have constants that will never change and will always represent the same value (think of mathematical values like PI) go with constexpr.
If all instances of a class should share a constant value, I'd recommend against using static const, since it would be defined at runtime, but it will always have the same value, right? Just use static constexpr instead.
Finally, I mentioned namespaces at the start of this answer. Sometimes, you might want a group of associated constants that don't necessarily belong to a class. For instance, while PI is used in circles, it doesn't necessarily mean that I want to include the circle class' header every time I want PI. But I don't want to have a "raw" PI variable name in my project's namespace! That's just asking for trouble. Instead, consider surrounding your constants in a namespace block to emulate the syntax used to call a class' member!
// YourHeader.h
#ifndef YOUR_HEADER_H
#define YOUR_HEADER_H
namespace MyConstants
{
constexpr int a = 1;
constexpr int b = 2;
}
#endif
// main.cpp
#include <iostream>
#include "YourHeader.h"
int main()
{
std::cout << MyConstants::a << "\n"; // 1
std::cout << MyConstants::b << "\n"; // 2
}
Note that we didn't use static with a namespace, we don't need to since we're not using a class or struct, we're simply wrapping them in the namespace to avoid naming conflicts. static would do something else here. See this post for more info on that.
Extra Note: While it is possible to declare a variable as a constexpr const, I wouldn't recommend it as it does the same as simply declaring it constexpr. Do note that constexpr when combined with pointers will turn the pointer into a constant pointer to a constant value! See this post for more details on that.
Why do you feel that you need a class for this? That doesn't seem appropriate. FORTRAN comparisons are also not likely to bear much fruit as C++ is a different language with different idioms and concepts.
To me, it seems like you should simply put those constants in a header file. Be sure to make them static const constexpr to avoid linker clashes.
// Constants.hpp
#ifndef MYLIB_CONSTANTS_HPP
#define MYLIB_CONSTANTS_HPP
#pragma once
static constexpr const int Number_0 = 234;
static constexpr const float Number_1 = 34.76;
static constexpr const double Number_2 = 98.78;
#endif
Now you just #include "Constants.hpp" in any translation unit that requires access to these values.
For the record, the old-school C approach to do the same thing would be to use #defines.
Don't forget to give these constants meaningful names.

Creating a class member that is automatically calculated from other class members?

I'm an absolute newbee when it comes to programming and I'm trying to teach myself the basics by just solving some easy "problems" in C++.
I have searched the web for an exact answer to my question before posting it here and haven't found one so far, however that may be because of (1).
So, what I'm looking for is a way to declare a class member that gets automatically calculated from other members of the same class, so that the calculated class member can be used just like an explicitly defined class member would. For example imagine a struct called creature that has the properties/members creature.numberofhands, creature.fingersperhand and finally the property creature.totalfingers that automatically gets calculated from the above members.
Heres an example of the closest I got to what I wanted to achieve:
#include <iostream>
typedef struct creature {
int numberofhands;
int fingersperhand;
int totalfingers();
} creature;
int creature::totalfingers()
{
return numberofhands * fingersperhand;
};
int main()
{
creature human;
human.numberofhands = 2;
human.fingersperhand = 5;
printf("%d",human.totalfingers());
return(0);
}
What's really annoying me about this, is that I have to treat the calculated one DIFFERENTLY from the explicitly defined ones, i.e. I have to put "()" after it.
How can I change the code, so I can use: human.totalfingers without ever explicitly defining it?
The simplest option would be to use public member functions and make the actual properties hidden.
Something like this:
class Creature {
public:
Creature(int numhands, int fingersperhand) // constructor
: m_numhands{numhands}, m_fingersperhand{fingersperhand}
{ }
int fingersPerHand() const { return m_fingersperhand; }
int numberOfHands() const { return m_numhands; }
int totalFingers() const { return numberOfHands() * fingersPerHand(); }
private:
const int m_numhands;
const int m_fingersperhand;
};
The private member variables are an implementation detail. Users of the class just use the three public member functions to get the different number of fingers after construction and don't need to care that two of them are returning constant stored numbers and the third returns a calculated value - that's irrelevant to users.
An example of use:
#include <iostream>
int main()
{
Creature human{2, 5};
std::cout << "A human has "
<< human.totalFingers() << " fingers. "
<< human.fingersPerHand() << " on each of their "
<< human.numberOfHands() << " hands.\n";
return 0;
}
If - as per your comment - you don't want to use a constructor (although that's the safest way to ensure you don't forget to initialize a member), you can modify the class like this:
class CreatureV2 {
public:
int fingersPerHand() const { return m_fingersperhand; }
int numberOfHands() const { return m_numhands; }
int totalFingers() const { return numberOfHands() * fingersPerHand(); }
void setFingersPerHand(int num) { m_fingersperhand = num; }
void setNumberOfHands(int num) { m_numhands = num; }
private:
// Note: these are no longer `const` and I've given them default
// values matching a human, so if you do nothing you'll get
// human hands.
int m_numhands = 2;
int m_fingersperhand = 5;
};
Example of use of the modified class:
#include <iostream>
int main()
{
CreatureV2 human;
std::cout << "A human has "
<< human.totalFingers() << " fingers. "
<< human.fingersPerHand() << " on each of their "
<< human.numberOfHands() << " hands.\n";
CreatureV2 monster;
monster.setFingersPerHand(7);
monster.setNumberOfHands(5);
std::cout << "A monster has "
<< monster.totalFingers() << " fingers. "
<< monster.fingersPerHand() << " on each of their "
<< monster.numberOfHands() << " hands.\n";
CreatureV2 freak;
freak.setFingersPerHand(9);
// Note: I forgot to specify the number of hands, so a freak get
// the default 2.
std::cout << "A freak has "
<< freak.totalFingers() << " fingers. "
<< freak.fingersPerHand() << " on each of their "
<< freak.numberOfHands() << " hands.\n";
return 0;
}
Note: all of the above assumes you are using a modern C++14 compiler.
What you have described is one of the reasons why encapsulation and "member variables should be private" is the recommended way of doing things in C++.
If every variable is accessed through a function, then everything is consistent, and refactoring from a member variable to a computation is possible.
Some languages, like C# or D, have the concept of "properties", which provide a way around the issue, but C++ does not have such a construct.
For fun, the proxy way to avoid extra parenthesis, (but with some extra costs):
class RefMul
{
public:
RefMul(int& a, int& b) : a(a), b(b) {}
operator int() const { return a * b; }
private:
int& a;
int& b;
};
struct creature {
int numberofhands;
int fingersperhand;
RefMul totalfingers{numberofhands, fingersperhand};
};
Demo
Note: to use RefMul with printf, you have to cast to int:
printf("%d", int(human.totalfingers));
That cast would not be required if you use c++ way to print:
std::cout << human.totalfingers;
If you're after consistency, you can make your changes the other way around. Replace the two member variables with constant methods which simply return copies of the member variables. That way, the way you access data is consistent and you don't have to worry about some code changing the values of the member variables when it shouldn't.
Others have provided very good answers. If you are looking for consistency, probably the easiest way is to make use of member functions (as #Jesper Juhl has answered).
On the other hand, if you strictly want to use class members that are calculated automatically from other members, you can use properties. Properties (as are defined in C# and Groovy) are not a standard feature of C++ but there are ways to implement them in C++. This SO question has a very good overview of the ways that properties can be defined and used in C++. My favorite way of defining properties is taking advantage of Microsoft-specific extension for properties in Visual C++ (obviously, this approach is specific to Microsoft Visual C++). A documentation of properties in Visual C++ can be found in MSDN. Using properties in Visual C++, your code can be modified to:
struct creature {
int numberofhands; // use of public member variables are generally discouraged
int fingersperhand;
__declspec(property(get = get_totalfingers)) // Microsoft-specific
int totalfingers;
private:
int fingers;
int get_totalfingers()
{
return numberofhands * fingersperhand; // This is where the automatic calculation takes place.
}
};
This class can be used like this:
#include <iostream>
int main()
{
creature martian;
martian.numberofhands = 2;
martian.fingersperhand = 4; // Marvin the Martian had 4!
// This line will print 8
std::cout << "Total fingers: " << martian.totalfingers << std::endl;
return 0;
}
As I said earlier, properties are not a standard feature of C++ but there are ways to get them in C++ which either rely on smart tricks or using compiler-specific features. IMHO, using simple functions (as #Jesper Juhl described) is a better alternative.

Why/When would I want to use a class data member without defining an object of the class?

It is possible in C++ to use a data member of a class without defining an object of that class, by defining that data member in the public section as a static variable, as in the code sample below. The question is, why/when would I want to do this? and how can I do it?
class ttime{
public:
ttime(int h=0, int m=0, int s=0):hour(h), minute(m), second(s){} //constructor with default intialization
int& warning(){return hour;}
void display()const{cout<<hour<<"\t";}
static int hello;
~ttime(){}
private:
int hour;
int minute;
int second;
};
main()
{
ttime:: hello=11310; //Is this the way to use hello without creating an object of the class?
cout << ttime:: hello;
ttime hi(9);
hi.display();
hi.warning()++;//the user is able to modify your class's private data, which is really bad! You should not be doing this!
hi.display();
}
Declaring a class member variable as static essentially makes it a singleton object that is shared by all of the instances of that class. This is useful for things like counters, semaphores and locks, and other types of data that need to be shared by the other class members.
Declaring it public makes it accessible to all users of that class. It's generally a bad idea to allow class variables to be modifiable by functions outside the class, though.
Declaring it const, on the other hand, is the usual way to provide publicly readable constants for the class.
Example
Your library class:
class Foo
{
public:
// Version number of this code
static const int VERSION = 1;
private:
// Counts the number of active Foo objects
static int counter = 0;
public:
// Constructor
Foo()
{
counter++; // Bump the instance counter
...
}
// Destructor
~Foo()
{
counter--; // Adjust the counter
...
}
};
Some client of your library:
class Bar
{
public:
// Constructor
Bar()
{
// Check the Foo library version
if (Foo::VERSION > 1)
std::cerr << "Wrong version of class Foo, need version 1";
...
}
};
In this example, VERSION is a static constant of the class, which in this case informs the outside world what version of the code is contained in the class. It's accessed by the syntax Foo::VERSION.
The static counter variable, on the other hand, is private to the class, so only member functions of Foo can access it. In this case, it's being used as a counter for the number of active Foo objects.
As cited before, static member variables work as 'global' variables, but within the class namespace.
So it is useful for counters or shared resources between objects.
In the case of 'public static' modifier, it is easy to see its use within libraries to provide access to constants and general-purpose functionality (static methods).
For example, an input library might have:
class KeyEvent
{
public:
static const int KEY_DOWN = 111;
static const int KEY_UP = 112;
...
}
//And then in your code
#include <KeyEvent>
void poolEvent(Key *key)
{
if(key->type() == KeyEvent::KEY_DOWN)
...
}
I am not familiar with the c++ syntax for statics at the moment. But in c++-cli (.net, Visual C++) the :: is correct.
For the purpose of statics:
There are many cases where it makes sense to use them. In general, when you want to store information that belong to the class itself (meaning to all objects of the class) and not to a single object/instance.
Even though not originally invented for this purpose, static constexpr data members of structs are a backbone of template meta-programming. Just check out the limits standard library header as a simple example.
For example, we can define a wrapper around the builtin sizeof operator. While rather useless in itself, it hopefully gives the right idea.
#include <iostream>
template<typename T>
struct Calipers
{
static constexpr auto size = sizeof(T);
};
int
main()
{
std::cout << "short: " << Calipers<short>::size << "\n";
std::cout << "int: " << Calipers<int>::size << "\n";
std::cout << "long: " << Calipers<long>::size << "\n";
std::cout << "float: " << Calipers<float>::size << "\n";
std::cout << "double: " << Calipers<double>::size << "\n";
}
Possible output:
short: 2
int: 4
long: 8
float: 4
double: 8
It is similar to a global variable, only that it is not defined at the global namespace.
You find it in C++ code that was written before namespaces were introduced, or in template meta programming were it is more useful.
In general, I would not recommend to use it as in your example and would prefer to avoid global state as much as possible. Otherwise, you end up with code that is difficult to test.

C++ can't establish communication between variables in separate functions

I am making a text-based RPG with C++ and I'm having the same error pop up time and again, and I'm sure I'm doing something fundamentally wrong, but I don't know what. Searches turned up the solution to the specific compiler error, but not anything I can use to fix the code I'm writing.
Question I want answered: How do I use pointers to enable communication of variables between separate functions? In other words, how can I use pointers to point to a variable's value so that I can use and manipulate that value in a function in which it was not declared?
TL;DR version: I'm trying to make my "exp" int variable communicate with outside functions using pointers. I get the error "ISO C++ forbids comparison between pointer and integer [-fpermissive]"
Long version: Here's a bit of the code where I'm having problems:
In file charlvl.cpp:
...
int lvl = 1;
int *exp = 0;//value I want communicated to main()
int str = 0;
int vit = 0;
...
in file fight.cpp (main.cpp):
...
//you've just killed a monster
cout << "\nThe monster drops to the ground." << endl;
cout << "You gained " << expValue << " experience!" << endl;
&exp += expValue;//&exp is the character's experience.
//expValue is the exp gained upon monster death
//*exp (from charlvl.cpp) is the value I want to communicate to here.
It was not declared here, but in charlvl.cpp. How do I establish communication between the declared variable in charlvl.cpp and main() without having to resort to using global variables?
If you defined exp as a global pointer, you don't need to think about the communication thing, you can just simply use it in different functions, but the way you use it is wrong.
&exp += expValue;
should be change to
*exp += expValue;
because * means get that pointer's content to me.
btw, try not defining exp as a pointer may also work.
int exp = 0;
exp += expValue;
This is all based on exp is a global var or global pointer.
if you have defined it in a function like this:
void func()
{
int *expPtr = 0;
int exp = 0
}
And you want to use it in another function
void use()
{
// trying to use expPtr or exp.
}
The ways I know is:
1, use a local var and return it in func(), but be aware that the returned var is only a copy.
int func()
{
int exp = 0;
exp++;
return exp;
}
2, use a local pointer and allocate memory for it, then return the pointer or assign the new memory to a global pointer. But be careful about the memory leak, you need to delete it as soon as you don't use it.
int * func()
{
int *expPtr = 0;
expPtr = new int(2);
return expPtr;
}
You've gotten the & and * operators confused. * turns an int* into an int, while & turns an int* into an int**.
This is what you want:
(*exp) += expValue;
You might want to consider using references.