const correctness and vector

Started by
2 comments, last by Miserable 19 years, 1 month ago
Ok I have a simple method that adds a Node* to a vector<Node*>.

void Node::addDependantRes(const Node* res)
{
    dependants.push_back(res);
}

This gives me an error. My understanding of const Node* res is that the object being pointed to cannot be modified through res, which it isnt, unless push_back() works way different than I think. Any help? Also, making a method const means that no changes will occur to *this? Thanks.
Advertisement
can you post the error?
the vector would need to be
std::vector<const Node *> dependants;

pretty much the same reason you can't do:

const Node *pF = new Node;
Node *pF2 = pF;

unless pF2 was const as well, or pF is not const.
Quote:Original post by AcidInjury
Ok I have a simple method that adds a Node* to a vector<Node*>.

*** Source Snippet Removed ***

This gives me an error. My understanding of const Node* res is that the object being pointed to cannot be modified through res, which it isnt, unless push_back() works way different than I think.

You attempt to store it in a vector<Node*>, which means that you will be retrieving non-const pointers to it, and it can be modified through them. As was pointed out, you need a vector<const Node*> (or take a non-const pointer).

Quote:Also, making a method const means that no changes will occur to *this?

Yes. (Except for members marked mutable.)

This topic is closed to new replies.

Advertisement