0

Accessing class parameters and functions through the iterator fails, both when using -> and *. Searched a lot of threads to no avail. It wont let me submit the question unless more details are added so, hmm, co stands for connection and have been double checking const and pointer references all day.

Snip:

vector<Axon>::iterator ait;
ait=axl.begin();
const Neuron* co=ait->get_conn();

Diet compilable code:

#include <iostream>
#include <vector>
using namespace std;

class Neuron;
class Axon;
class Neuron{
friend class Axon;
public:
    Neuron(int);
    void excite(double);
    void connect(const Neuron *);
    //void grow_ax();
private:
    double _exc;
    vector<Axon> axl;   
};
class Axon{
    friend class Neuron;
public:
    Axon();
    const Neuron* get_conn();
private:
    double cond; //conductivity
    const Neuron* connection;
};
Neuron::Neuron(int numax){
        _exc=0;
    vector<Axon> axl (numax,Axon());
}
Axon::Axon(){
    cond=1;
    connection=0;
}
void Neuron::connect(const Neuron * nP){
    vector<Axon>::iterator ait;
    ait=axl.begin();
    const Neuron* co=ait->get_conn(); //error is here,
    //if (ait->connection==0)           these don't work
            //ait->connection=nP;       <===
}
const Neuron* Axon::get_conn(){
    return connection;
}

int main(){
    Neuron n1=Neuron(1);
    Neuron n2=Neuron(0);
    Neuron* n2p=&n2;
    n1.connect(n2p);
}

Thanks in advance

1
  • Have you tried printing axl.size(), or checking ait==axl.end(), to see if you've correctly initialized your vector with an element in it? Commented Jun 22, 2013 at 16:59

1 Answer 1

1
ait=axl.begin();
const Neuron* co=ait->get_conn();

axl doesn't contain any elements, so, axl.begin() == axl.end() and you're dereferencing it. Derefencing std::vector::end() is an undefined behavior.

Look at your constructor:

Neuron::Neuron(int numax){
    _exc=0;
    vector<Axon> axl (numax,Axon());
    // this is a declaration of local object
    // which will be destroyed at the end of the constructor
}

Note also, this:

Neuron n1=Neuron(1);
Neuron n2=Neuron(0);

Should be

Neuron n1(1);
Neuron n2(0);
Sign up to request clarification or add additional context in comments.

2 Comments

How are they declared properly to avoid destruction?
Just change vector declared in the class by calling axl.push_back(Axon()) in the constructor for example.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.