using a member variable before its declaration? [duplicate] - c++

This question already has answers here:
Do class functions/variables have to be declared before being used?
(5 answers)
Closed 6 years ago.
is it possible to use a member variable of a class before declaring it?
here is my code.
using namespace std;
class Computer
{
public:
Computer()
{
processor_speed = 0;
}
~Computer();
void setspeed (int);
int getspeed (void);
private:
int processor_speed;
};
/*Computer::Computer()
{
processor_speed = 0;
} */
Computer::~Computer()
{
cout<<"this is a destructor"<<endl;
}
void Computer:: setspeed(int p)
{
processor_speed = p;
}
int Computer::getspeed(void)
{
return processor_speed;
}
int main(void)
{
Computer obj;
cout<<"processor speed is "<<obj.getspeed()<<endl;
obj.setspeed(100);
cout<<"processor speed is now "<<obj.getspeed()<<endl;
return 0;
}
as u can see here i was able to use variable processor_speed before declaring it.
i saw a similar question here: Do class functions/variables have to be declared before being used?
but i was not able to understand the reason why this code work.
Thanks

Yes, you can do it.
A member variable is in scope for member functions of your class even if it is textually after its first point of use. The compiler translates your code in several "passes". One could think of it as getting all member variables first, and only then translating member functions, with all declarations in place.
Note that this is not allowed for "free-standing" global and static variables inside translation units: a declaration must precede the first use, otherwise you get an error.

Related

What is the difference between const vs static functions outside classes C++ [duplicate]

This question already has answers here:
Difference of static const and static when returning a static variable
(2 answers)
The static keyword and its various uses in C++
(9 answers)
Effect of return type being static
(3 answers)
Closed 5 months ago.
This is not related to classes. I have a function that returns a constant based on the input.
A minimum working example related to my question is added below.
#include <iostream>
namespace surfaceArea
{
constexpr int triangle = 11;
constexpr int square = 25;
}
int getSurfaceArea(bool isTriangle)
{
return isTriangle? surfaceArea::triangle : surfaceArea::square;
}
int main ()
{
const int numSides = 3;
const bool isTriangle = (numSides == 3);
const int surface = getSurfaceArea(isTriangle);
std::cout << "Surface Area is " << surface;
return 0;
}
Should I use static or const for the function getSurfaceArea(bool isTriangle). That is as
const int getSurfaceArea(bool isTriangle) or static int getSurfaceArea(bool isTriangle)? What are the differences between these two keywords and What is the best practice to use in a similar scenario?
Returning a const T where T is copyable and not a ref-type is almost never advised: your caller can simply assign it to another T and change the value. It brings no benefits.
When your global (non-member) function is static, it means it has implicit linkage. That is, it can only be called from the current C++ file. If you only have one C++ file, it doesn't matter; even if you have multiple, you might consider putting it to an anonymous namespace instead, if that's what you want. If you have no such intentions to keep it local to the current C++ file, then it shouldn't be static.

Declare a global object inside of a function (c++) [duplicate]

This question already has answers here:
Can a local variable's memory be accessed outside its scope?
(20 answers)
Closed 7 years ago.
I'm declaring objects of a struct inside of a function and i'd like to access said objects outside of that function (making them global). Here's an example of what i'd like to do
#include <iostream>
using namespace std;
struct exampleStruct
{
int ID;
};
void makeExampleStruct ()
{
exampleStruct exampleObj[30];
for (int r=0;r<=30;r++)
{
exampleObj[r].ID=r;
}
}
int main()
{
makeExampleStruct();
cout << exampleObj[1].ID << endl;
return 0;
}
This gives me a "'exampleObj' was not declared in this scope". I know i could simply declare the objects creation inside of main, but i'd rather keep it inside of a function so it's easier to read. Is there a way of doing that?
Thank you for your help
Try to declare the variable globally (outside of the function)
use the function to change the global variable.
Variables declared inside of a function are only accessible in that function; they are called local variables as they are local to the function in which they are declared.
The main() function cannot access the local variables of another function.
Globally declared variables are visible everywhere.
After the function is called, your array no longer exists:
void makeExampleStruct ()
{
exampleStruct exampleObj[30];
// exampleObj is created here
for (int r=0;r<=30;r++)
{
exampleObj[r].ID=r;
}
// exampleObj is destroyed here.
}
So even if you could access the object, it would be illegal to do so after the function returns, since the object's lifetime has ended.
No. You need to declare it outside the function otherwise it is local.
You cannot provide global access to local variables from functions. What you can do instead is something like making them static and return a reference:
exampleStruct[30]& makeExampleStruct () {
static exampleStruct exampleObj[30];
static bool isinitialized = false;
if(!isinitialized) {
for (int r=0;r<=30;r++) {
exampleObj[r].ID=r;
}
isinitialized = true;
}
return exampleObj;
}

C++ - using return when the function being called on has parameters [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 7 years ago.
Improve this question
I have a function like this:
void functiont(int a, int b)
{
if(playingnumber=="T")
{
returntransfer=1;
struct A
{
~A() // Destructor to run after returning variable
{
void cardselecth(int playingcolorh, int playingnumberh);
}
}
return returntransfer;
}
}
Anyway I need to grab that returned variable without calling on int a or int b. So in another function I write
newvar=functiont(int a, int b);
And it gives a compile error. I don't know how else to do this. I could write functiont(a,b); and I get an error; I write functiont(int,int); and get an error. I've tried writing functiont(); but then it assumes the function's in the same file and I haven't defined it, which it isn't (I'm transferring across files here, so I need to define any parameters so it knows to refer to another file).
I'm not sure what you want to do there, but at first this function is a void function so it can only return but not return a value. So your signature, respectively the void must be changed according to the type you want to return.
In this case
int functiont(int a, int b)
would be appropriate.
When calling the function you have to pass it two arguments of type integer.
newvar = function(1, 2);
It's a good idea to post the error, too. Best regards
If you prefer to return an int, return type of your function should be int not void. I corrected the code as follows. Note the changes with comment
int functiont(int a, int b)
{
int returntransfer=0; //change , declaration out of if block
// to maintain the scope of variable
if(playingnumber=="T")
{
returntransfer =1;
}
return returntransfer;//change
}
You can declare a struct variable inside a function, but it don't mean just by declaration it will be get called.
struct A
{
~A() // Destructor to run after returning variable
{
void cardselecth(int playingcolorh, int playingnumberh);
}
};//change added ; at end of declaration.
EDIT
Adding complete program for answer to further questions:
#include<iostream>
#include<string>
int functiont(int a, int b)
{
int returntransfer=0; //change , declaration out of if block
// to maintain the scope of variable
std::string playingnumber ="T"; //Added again for completness
if(playingnumber=="T")
{
returntransfer =1;
}
struct A
{
~A() // Destructor to run after returning variable
{
void cardselecth(int playingcolorh, int playingnumberh);
}
};//change added ; at end of declaration.
return returntransfer;//change
}
int main()
{
std::cout<<functiont(2,3);
}

how to refer to the global namespace [duplicate]

This question already has an answer here:
c++ use default functions in class with same name
(1 answer)
Closed 8 years ago.
Inside a method isGood I want to use function isGood from the global namespace. How do I avoid to have isGood interpreted as the same method instead of the global function ?
bool isGood(){ return_if_it_is_good;}
class X{
int a;
bool isGood(){return isGood(a);}
}
Call with the :: operator :
bool isGood(){ return_if_it_is_good;}
class X{
int a;
bool isGood(){return ::isGood(a);}
}

C++: member call to non-static member function pointer [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
C++ member-function pointer
How to invoke pointer to member function when it's a class data member?
I've only recently started using C++, so I apologize if the following contains any trivial mistakes, or if I missed an easier solution. I would like to achieve something like this:
class ClassA {
typedef double (ClassA::*CondFunc)();
public:
ClassA(int x, int y) {
value_ = x;
switch (y) {
case 0:
condFunc_ = &ClassA::condA;
break;
case 1:
condFunc_ = &ClassA::condB;
default:
break;
}
}
~ClassA();
int value_;
CondFunc condFunc_;
double condA() { return 2.0*value_; }
double condB() { return 4.0*value_; }
void Test() {
int a = condFunc_(); // compile error
}
};
but get a compile error in Test(). Please note that this is a vastly simplified function and is not supposed to make any sense. I've searched this forum and elsewhere for answers, but am still not sure whether defining/calling such non-static member function pointers is even possible. The only plausible hint/solution I've come across employs a static wrapper function to achieve something similar. I'd be grateful for any help/clarifications.
You have to call the member pointer function like this:
int a = (this->*condFunc_)();