How to access a private variable which is within a function [closed] - c++

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
#include <iostream>
using namespace std;
class Test{
public:
int kk(int b){
return a=b+5;
}
private:
int a;
/*void priv()
{
int a; // How to access a , if this part was not commented
}*/
};
int main()
{
Test kris;
cout<< kris.kk(5)<<endl;
return 0;
}
I was trying to understand the concept of private and public members and the methods to access the private members when they are defined in a class. I wanted to rephrase the question to how to access a variable, which is local to a private function via an object of class "Test" (as defined in the code).
I found the answer to it and experimented it with my own code and i was able to execute the code. Below is the code
#include <iostream>
using namespace std;
class Test{
public:
int xyz_1(){
return xyz_2() ;
}
private:
int xyz_2(){
int a=5;
return a;
}
};
int main()
{
Test kris;
cout<< kris.xyz_1()<<endl<<"Sorry for the confusion"<<endl;
return 0;
}

How to access a private variable which is within a function
You're trying to access a local variable of priv() in the function kk() which is impossible unless the visibility of the variable a is either public or outside the function (in case with classes) under private: (which will make it accessible to all member functions). In a rough way, you're trying to do something:
void fun1() {
int a;
}
void fun2() {
std::cout << a;
}
Which is not possible.

You might need to think more about your design and what you achieve.
Do you want to have a private member in the class to access the function? Then declare your variable "a" as a private member in your class, and use this.a inside your function. If you want a child class to be also able to access your private member, make the variable protected instead of private.
If you want to restrict any other function in your class from accessing that member, then I would be curious about what your intention is. If you try to hide the implementation you might want to look into the Pimpl technique. However, it also has a very specific use case (besides that you can use it to hide the implementation from developers, too).
https://en.cppreference.com/w/cpp/language/pimpl[pimpl programming technique]1
If you add more information about your problem and intention I'm sure people can give you better directions.

Related

How to create functions to manipulate objects inside objects with protected or private atributes? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I'm trying to learn about classes/inheritance(in general), so I'm trying to make a game as a semester final project.
Lets say I have a class SOLDIER with an object of a class INVENTORY with an object of a class POTION (with size and amount).
If I want to make a function use_potion(), how do I do that? I could have everything public to make something like "soldier1.addlife(soldier1->inventory1->potion1->size), but that looks like a terrible practice. How do I do implement that with private/protected atributes?
*The potion is only 1 of the functions I will need to make with the same structure - object->object->object->something -, so I really need some help and examples to understand how to make them.
You need to add a public function in your SOLDIER class that invoke public function in INVENTORY object that invoke public function in POTION obj.
Here is an example structure of your program:
class SOLDIER
{
private:
class INVENTORY
{
private:
class POTION
{
int size = 5;
public:
void use_potion()
{
size++;
printf("use_potion in POTION obj");
}
};
POTION pot;
public:
void use_potion()
{
pot.use_potion();
}
};
INVENTORY inv;
public:
void use_potion()
{
inv.use_potion();
}
};
int main()
{
SOLDIER s;
s.use_potion();
return 0;
}

C++ access violation when writing to typdef struct [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I have a struct defined in a header file. Then I have a singleton class where I am trying to use the struct. When I call ResetVars() from another class I get an access violation when it hits the line that says test.numResponses = "TEST". I am assuming this has something to do with initialization but I haven't been able to solve it. I am new to c++ and I have no idea how to get around this. Thanks for any help.
struct.h
typedef struct POLL_DATA
{
std::string numResponses;
std::string type;
std::string question;
} POLL_DATA;
ControlPolls.h
class ControlPolls
{
private:
static bool instanceFlag;
static ControlExitPolls *controlSingle;
ControlExitPolls();
POLL_DATA test;
public:
static ControlExitPolls* getInstance();
void ResetVars();
};
ControlPolls.cpp
#include "ControlPolls.h"
bool ControlPolls::instanceFlag = false;
ControlPolls* ControlPolls::controlSingle = NULL;
//Private Constructor
ControlExitPolls::ControlExitPolls()
{
};
//Get instance
ControlPolls* ControlPolls::getInstance()
{
if(!instanceFlag)
{
controlSingle = &ControlPolls();
instanceFlag = true;
return controlSingle;
}
else
{
return controlSingle;
}
}
void ControlExitPolls::ResetVars()
{
test.numResponses = "TEST";
}
callingClass.cpp
ControlPolls *controlSingleton;
controlSingleton = ControlPolls::getInstance();
controlSingleton->getInstance()->ResetVars();
You've been struck by C++'s Most Vexing Parse, a compiler rule that says anything that could be a function declaration is a function declaration. The culprit is this line:
POLL_DATA testPoll();
testPoll is treated as the declaration of a function with return type POLL_DATA. Try removing the brackets, or writing simply POLL_DATA testPoll; which implicitly calls the compiler-generated default constructor.
Another larger problem is that testPoll is a member of A, but you've hidden it and declared a local variable in your constructor, A::A(). I suggest you remove the constructor altogether because the implicit constructor will suffice.
Some more notes on your code:
You've declared your class a but refer to it later as A.
You've written an implementation of a constructor for A without declaring it like a proper forward declaration.
Also, typedef struct is not needed in C++. It is sufficient and encouraged to write:
struct POLLDATA {
...
};

Is there anyway in c++ to make a function of a class who's objects each do something different for that function? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
Just some background:
I am making a monopoly game and now I have to implement the actions of each space such as GO, properties (upgrading), chance, community chest, jail, etc.
I've considered making a different class for each space (but obviously that would be very time consuming). I believe there is also a way do to it with inheritance and pure virtual functions. Any way you guys can think that would make this a simpler process?
Thanks!
There are only a few different types of spaces:
properties
railroads
chance / community chest
utilities
other single ones like go, jail, parking, tax
For example you could have a Property class where each instance of the class has a different name/colour/price. You wouldn't have to make 22 different classes, just have 22 instances of the same class with different names.
Note that having class instances that represent spaces you can land on is only one way to implement a game like that. I'm pretty sure I wouldn't choose that option.
There are two ways you can make a function do different things given an object:
Differentiate the behavior based on the data of the object.
You could capture the differences in the various spaces using data.
enum SpaceType
{
GO, CHANCE, COMMUNITY_CHEST, // etc...
};
class Space
{
public:
void foo()
{
switch (spaceType)
{
case GO:
// DO stuff for GO
break;
case CHANCE:
// DO stuff for CHANCE
break;
// etc..
}
}
private:
SpaceType spaceType;
}
Differentiate the behavior based on the type of an object.
class Space
{
public:
virtual void foo() = 0;
};
class GoSpace : public Space
{
public:
virtual void foo()
{
// Do stuff for GO
}
};
class ChanceSpace : public Space
{
public:
virtual void foo()
{
// Do stuff for CHANCE
}
};
// Similarly for other classes.
Pick your method. Personally, I would pick the second method because the logic for each different type is put into their own functions, without the complications of what other types do.

How would you structure the class interactions in a physics engine? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I'm writing a physics engine in C++ and I've come to a stop, namely how I should design the class hierarchy. What I'm specifically concerned about is the World and Body classes. Body should expose some details to World that World then can work on. But at the same time, I don't want users to be able to access all of those properties of Body. But I still want users of the engine to be able to change some things in a body. For example, its position. How would you structure this in terms of classes?
Define an interface (i.e. a pure virtual class) that specifies what functions you want exposed from Body. Have Body implement that inteface.
Allow that interface, and not Body to be used from World.
This pattern is called composition.
Recently, I've solved a similar problem by introducing a special interface for the restricted operations, and inheriting protectedly from it. Like this:
struct RestrictedBodyFunctions
{
virtual void step() = 0;
virtual Body& asBody() = 0;
};
struct Body : protected RestrictedBodyFunctions
{
static std::unique_ptr<Body> createInWord(World &world)
{
auto Body = std::unique_ptr<Body>{new Body()};
world.addBody(*body); // cast happens inside Body, it's accessible
return std::move(body);
}
std::string getName() const;
void setName(std::string name);
protected:
void step() override
{ /*code here*/ }
Body& asBody() override
{ return *this; }
};
struct World
{
void addBody(RestrictedBodyFunctions &body)
{
m_bodies.push_back(&body);
}
void step()
{
for (auto *b : m_bodies)
{
myLog << "Stepping << " b->asBody().getName() << '\n';
b->step();
}
}
private:
std::vector<RestrictedBodyFunctions*> m_bodies;
};
That way, users can create Body objects using createInWorld, but they only get a handle to (the public part of) Body, while the World gets its handle to RestrictedBodyFunctions.
Another option you have is to reverse the above idea - provide a restricted public interface PublicBody, and have Body derive from PublicBody. Your internal classes will use the full Body, while factory functions make sure only PublicBody-typed handles are available to the clients. This alternative is a more simple design, but provides less control over who can access the full functionality.

How this program implements the concept of abstraction? [duplicate]

This question already has answers here:
What is abstraction? [closed]
(4 answers)
Closed 10 years ago.
Today,i was searching about abstraction and i got this example....how this program implements the concept of abstraction and please also elaborate what is abstraction in c++
#include <iostream>
using namespace std;
class Adder{
public:
// constructor
Adder(int i = 0)
{
total = i;
}
// interface to outside world
void addNum(int number)
{
total += number;
}
// interface to outside world
int getTotal()
{
return total;
};
private:
// hidden data from outside world
int total;
};
int main( )
{
Adder a;
a.addNum(10);
a.addNum(20);
a.addNum(30);
cout << "Total " << a.getTotal() <<endl;
return 0;
}
It should be called data abstraction, which is the key source of OOP(not limited to C++).
Quoted from wikipedia:
Data abstraction enforces a clear separation between the abstract
properties of a data type and the concrete details of its
implementation.
In your example, Adder is a data abstraction of an adder, which has two interfaces: addNum and getTotal. This abstraction hides(or encapsulates) the private data(total in this case), only expose its kernel behavior: adding a number and returning the current sum.
You are accessing the public methods for doing your tasks without knowing how the private members are affected. this is nothing but abstraction .
You are moving your hand without knowing how your mind instruct it to move.
Data Abstraction : Hiding unnecessary details . in your case you hide how the total is calculated. you just call the function and your task is done.
Data Encapsulation: Binding data with object. In your case you binded the total with object a. so it's not accessible without a permission.
Think of the constructor and function prototypes only:
class Adder {
Adder(int i);
void AddNum(int num);
int getTotal();
};
The implementation is hidden, abstracted away, and only the prototypes remain.