Does the addresses of the pointers change under certain cases [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 4 years ago.
Improve this question
If I make a vector of pointers of type of some defined class and put a pointer to an object of type of an inherited one of the first one in it, wont the pointer pointing to next address be changed to point to shifted address because of existence of new data members in the inherited class pointed by the previous one.
so If I defined an array with new of type of the base class and then put an object of type of the driven class, how would compiler deal with the modification of the start of the address of the next pointer. shouldn't it be shifted or something like that to make some bytes available for the previous one.

If you define a std::vector<BaseClass> where BaseClass is your base class and then put a DerivedClass type into that vector where DerivedClass is your derived class, you will get slicing. Meaning any extra data members in the derived class are lost.
Because of that, what you would normally do is define a std::vector<BaseClass *> which is a vector of base class pointers. Now you can put base class pointers and derived class pointers in your vector and there is no slicing.
You are storing pointers in the vector. All pointers are the same size.
Note, in the real world you would probably not user raw pointers but some version of a smart pointer to reduce the chance of memory leaks (i.e. forgetting to free a pointer).

Related

C++ data members: Value vs. Pointer [duplicate]

This question already has answers here:
Why should I use a pointer rather than the object itself?
(23 answers)
Closed 3 years ago.
I am beginning development on a substantial personal project and wanted to ask a question regarding data members before doing so.
I am cognizant of the big differences between references and pointers. However, in my recent research, I have not found much (if any) clarification on the differences between data member values and pointers.
Consider the following two class definitions:
class A
{
private:
const std::string someString_;
};
class B
{
private:
const std::string *someString_;
};
What are the differences/nuances between the member data of classes A and B? Informed answers and relevant articles would be highly appreciated.
Similar question has been made here.
Basically, by using value you make a copy and by using pointer you hold a memory address.
A copy means that you already have an instance of the variable type and just copy its contents when you do an assignation.
A pointer means the variable can hold the memory address of an instance or null (none instance or invalid state). You can edit the value or the contents of a pointer. By modifying the value you're holding another memory address, by modifying the contents of a pointer you're actually editing the contents at that memory address.
In fact, the class A you showed, creates a std::string when it is instantiated. And the class B just has an address to a std::string.
You can play with the A's someString_ from the A's constructor. But, you should make a new std::string or pass a reference to a std::string in the B's constructor before attempt to modify the contents of B's someString_.

How to contain derived types in a vector? [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 8 years ago.
Improve this question
I am making a game in C++ and I want my Game class to hold all of the GameObjects. It has a vector of the abstract base GameObject class, but in order for it to hold derived types it must be a vector of pointers to GameObjects:
// Game.h
class Game {
private:
std::vector<GameObject*> gameObjects;
public:
void addGameObject(GameObject* gameObject) {
gameObjects.push_back(gameObject);
}
}
The problem that arises happens when I want to add GameObjects to the vector. When I pass in a pointer to addGameObject, the pointer becomes NULL in the other scope. So I would like for the pointer to be stored in the vector, but not become NULL immediately afterwards. I do not know how I could get around this problem. Any ideas?
Edit: Thank you all for commenting. I have used C++ for a while now but I am new to using pointers and do not fully understand them yet. I knew that you needed to use them to create the vector that held the derived objects. I guess I need to research pointers a lot more.
"The problem that arises happens when I want to add GameObjects to the vector. When I pass in a pointer to addGameObject, the pointer becomes NULL in the other scope."
I can't tell why these pointers become NULL in the other scope, as you don't mentioned enough context to proove this.
But I think the better choice seems to be using a smart pointer like this
// Game.h
class Game {
private:
std::vector<std::shared_ptr<GameObject>> gameObjects;
public:
void addGameObject(std::shared_ptr<GameObject> gameObject) {
gameObjects.push_back(gameObject);
}
}
There are more choices for smart pointers, depending on your actual use cases for them, namely std::unique_ptr<GameObject> or std::weak_ptr<GameObject>.
std::shared_ptr<GameObject> (or the other mentioned smart pointer variants) should serve well for instances derived from GameObject class like e.g.
class Player : public GameObject {
// ...
};
This would manage references to your GameObject instance, as they are in use, or being owned in any scope.

Objects of a class derived from an abstract class should be in free store? [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 9 years ago.
Improve this question
I'm trying to wrap my head around what seems to be strange to me in TC++PL. It is about allocation of a class derived from an abstract class.
Since we don't know anything about the representation of an abstract type, we must allocate objects on the free store and access them through references and pointers.
Why free store? As you already know, a class derived from an abstract class can be allocated like any other local variables. I have no idea what exactly TC++PL tries to convey in this sentence.
In my opinion it is an incorrect statement. For example if you have an abstract base class B and derived (non-abstract) class D then you can write
D d;
B &b = d;
that is object of type D is created in stack provided that this code is in some function.
They mean that if you want to use some abstract class without knowing what concrete type that is, you must use dynamic allocation for it, i.e that you cannot write abstract_class A = concrete_class B;

Crash when copy a particular class [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Improve this question
I have a class really complicate, it has inside a vector of another class. I report one simpler, anyway it has inside the problem which I've been able to find.
// the inner class
class DuffyDuck{
int isblack; // 0 is white, 1 is black
int n_duck;
vector<DuffyDuck> * point_Duck;
public:
DuffyDuck(int isblack):isblack(isblack){
}
void set_point(vector<DuffyDuck> & Abitants){
point_Duck=&Abitants;
}
};
// the complessive class
class DuckCity{
vector<DuffyDuck> DuckAbitants;
public:
DuckCity(int numwhite,int numblack){
for(int i=0;i<(numblack+numwhite);++i){
DuckAbitants.push_back(DuffyDuck(i>=numblack));
DuckAbitants[i].set_point(DuckAbitants);
}
}
};
Now this works (i use point_Duck in several functions) but if I do something like that shown after once it's called in example "(*point_Duck)[2].n_duck;" in a function the project crashes.
That happens only if I do that:
DuckCity LittleTown(0,0);
LittleTown=DuckCity(3,5);
And after using some functions which call pointer.
If I do directly LittleTown(3,5) all is right.
I hope I explained well enough.
The DuffyDuck class is storing the address of a vector<> member of a DuckCity. Thus, when you copy the DuckCity to a different instance, that new instance will have a different vector<> instance. However, each DuffyDuck instance in that vector still has the address that was part of the old DuckCity instance.
So, your copy into littleTown yields dangling pointers.
I would recommend that you either rethink your design of DuffyDuck, or implement an assignment operator for DuckCity that performs a deep copy for each element of the vector<>. If you implement an assignment operator, remember to also follow the Rule of Three.
The cause of the problem is that each DuffyDuck has a pointer to a vector of DuffyDuck(s). When the class is destroyed the references become invalid --> crash.
DuckCity littleTown(1,2); // this creates a duck city
// with each duck pointing to the DuckAbitans vector.
littleTown=DuckCity(3,5); // this initializes another instance (call it INST)
// of DuckCity and
// then it assigns (via = operator) the value to littleTown
// by **copying** the DuffyDuck structures into a newly
// allocated vector. This makes the pointer of each DuffyDuck
// invalid after INST is destroyed (as it is a temporary object)
When you copy the address of Abitants, you are taking the address of the vector in the temporary object created by DuckCity(3,5). This temporary object is then copied into littleTown, and the original object destroyed. This means your original Abitats pointer is pointing at unused memory, which in turn leads to a crash.
It's hard to say exactly how you should fix this - probably by having a copy-constructor that "reconstructs" the Abitats pointer.

problems with c++ casting [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
Hello I have three classes
AbstSoccerTeam
PlayersSoccerTeam
PlayersFieldPlayerStates
PlayerSoccerTeam is a child class of AbstSoccerTeam.
bool AlanSoccerTeam::isClosestTeamMemberToSupportingPlayer(FieldPlayer* plyr)
is a method in player soccer team.
i am trying to call that method in the PlayersFieldPlayerStates class with this
PlayersSoccerTeam* sTeam;
sTeam->isClosestTeamMemberToSupportingPlayer(player);
I can get this problem when i run it
uninitialized local variable 'sTeam' used
I dont know whats going on or why i am getting this error.
Any help is apprecitated greatly
Thanking You
The problem is you have created a pointer to a PlayersSoccerTeam but you have not actually created the object itself yet.
I would suggest doing this.
PlayersSoccerTeam sTeam;
sTeam.isClosestTeamMemberToSupportingPlayer(player);
You could alternatively do this.
PlayersSoccerTeam* sTeam = new PlayersSoccerTeam()
sTeam->isClosestTeamMemberToSupportingPlayer(player);
As perhaps an interesting education experience create a constructor that prints something to stdout when it is run and then try doing these two options and yours to see what happens. A constructor will be run whenever a new object is created.
PlayersSoccerTeam* sTeam;
This line declares a pointer to a PlayersSoccerTeam and nothing else. All you get from this line is a pointer. It doesn't point anywhere in particular since you haven't initialized. There is no PlayersSoccerTeam anywhere to point to.
If you want an object of type PlayersSoccerTeam, then you just want:
PlayersSoccerTeam sTeam;
sTeam.isClosestTeamMemberToSupportingPlayer(player);
Since you told us about your hierarchy, it's possible that you want to use your PlayersSoccerTeam polymorphically as a AbstSoccerTeam. In this case you would need to use either a pointer or reference. This could be done like so:
AbstSoccerTeam* sTeam = new PlayersSoccerTeam();
// ...
delete sTeam;
Note that this still declares just a pointer, but the expression new PlayersSoccerTeam also creates a PlayersSoccerTeam object for the pointer to point to. Note that it's perfectly fine to assign a pointer to a PlayersSoccerTeam to a pointer to its parent AbstSoccerTeam - this is polymorphism in action. If you do this, you must make sure you delete sTeam; later, otherwise the object will be leaked.
A safer way to handle the user of dynamically allocated objects is to use a smart pointer, which you could do like so:
std::unique_ptr<AbstSoccerTeam> sTeam(new PlayersSoccerTeam());
Now you will not have to delete it because the std::unique_ptr takes care of that for you.